Wiki
Version 4 (modified by hopscc, 10 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 types (e.g nilable boolean, nilable int) test true if both non nil and the non nil object is 'true' (non false or non zero)

A nilable Object and nilable String (Object?, String? ) tests true if the instance is non-nil (no subsequent truth test beyond that)

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'
assert s  # succeeds if s is not nil


s1 as String ='...'   # non-nilable string with or without (0 length) value 
if s.length
    print 's not empty'
else
    print 's is length 0'
assert s1        # always succeeds - non nilable (warning)
assert s1.length # succeeds if s1 is not empty ( > length 0)


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

#nilable Object
shouldBeFalse as Object? = false  # bool value typed as nilable Anything
assert shouldBeFalse == false # ok
shouldBeTrue0 = not shouldBeFalse # tests against nil only 
assert shouldBeTrue0 == true  # fails assertion
shouldBeTrue = not (shouldBeFalse to bool)  
assert shouldBeTrue == true  # ok