Version 2 (modified by hopscc, 15 years ago) |
---|
Conditional Expressions
A conditional expression is an expression that produces a value that can be (conveniently) construed as a boolean
true or false value.
These are used directly in if and while flow control statements and the assert statement
Any of following can be used as conditional expressions and produce a boolean true value.
- non false (bool Type - expression or variable )
- numeric not 0
- non zero char
- not nil
- blank strings and empty collections are true (non nil) - must check .length for strings and .count for collections for checking non empty.
nilable objects (e.g nilable boolean, nilable int) test true if both non nil and non nil object is 'true' (non false or non zero)
Examples
a = 100 gt20 = a > 20 if a # numeric non zero print 'a non zero' if a > 10 # boolean condition print 'greater than 10' assert gt20 # boolean variable - succeeds true assert a > 20 # boolean condition same as above ch = c'x' if ch print 'ch non zero' assert ch ch=c'\0' if not ch # negated condition print 'ch is zero' s as String? # nillable string unset value if s print 's not nil' if s.length print 's not empty' else print 's is nil' l = [] # empty list assert l # succeeds not nil assert l.count # fails empty list ln as List?<of dynamic> # nillable list - unset assert ln # fails: ln not set so nil nb = a>10 to ? # bool expr cast to nillable bool assert nb # succeeds non nil and true nb = a<5 assert nb # fails a is >5 so variable is false nb = nil assert nb # also fails variable is nil