| 1 | = Conditional Expressions = |
| 2 | |
| 3 | A conditional expression is an expression that produces a value that can be (conveniently) construed as a boolean |
| 4 | true or false value. |
| 5 | these are used directly in '''if''' and '''while''' flow control statements and the '''assert''' statement |
| 6 | |
| 7 | Any of following can be used as conditional expressions and produce a '''boolean true''' value. |
| 8 | * non false (bool Type - expression or variable ) |
| 9 | * numeric not 0 |
| 10 | * non zero char |
| 11 | * not nil |
| 12 | * blank strings and empty collections are true (non nil) - must check .length for strings and .count for collections for checking non empty. |
| 13 | |
| 14 | nillable objects (e.g nillable boolean, nillable int) test true if both non nil and non nil object is 'true' (non false or non zero) |
| 15 | |
| 16 | == Examples == |
| 17 | |
| 18 | {{{ |
| 19 | a = 100 |
| 20 | gt20 = a > 20 |
| 21 | |
| 22 | if a # numeric non zero |
| 23 | print 'a non zero' |
| 24 | if a > 10 # boolean condition |
| 25 | print 'greater than 10' |
| 26 | assert gt20 # boolean variable - succeeds true |
| 27 | assert a > 20 # boolean condition same as above |
| 28 | |
| 29 | ch = c'x' |
| 30 | if ch |
| 31 | print 'ch non zero' |
| 32 | assert ch |
| 33 | ch=c'\0' |
| 34 | if not ch # negated condition |
| 35 | print 'ch is zero' |
| 36 | |
| 37 | s as String? # nillable string unset value |
| 38 | if s |
| 39 | print 's not nil' |
| 40 | if s.length |
| 41 | print 's not empty' |
| 42 | else |
| 43 | print 's is nil' |
| 44 | |
| 45 | l = [] # empty list |
| 46 | assert l # succeeds not nil |
| 47 | assert l.count # fails empty list |
| 48 | |
| 49 | ln as List?<of dynamic> # nillable list - unset |
| 50 | assert ln # fails: ln not set so nil |
| 51 | |
| 52 | nb = a>10 to ? # bool expr cast to nillable bool |
| 53 | assert nb # succeeds non nil and true |
| 54 | nb = a<5 |
| 55 | assert nb # fails a is >5 so variable is false |
| 56 | nb = nil |
| 57 | assert nb # also fails variable is nil |
| 58 | |
| 59 | }}} |
| 60 | |