Wiki

If Expression

The if expression evaluates to exactly one of two expressions based on a condition.

Grammar

if( <condition>, <texpr>, <fexpr>)

If the condition is true, texpr is evaluated; otherwise fexpr is evaluated. The condition is always evaluated and subsequently texpr or fexpr will be unless condition threw an exception.

Note that there can be no space between the 'if' and the '(' - there is a single token 'if('.

The type of the if expression is the greatest common denominator between the type of texpr and the type of fexpr.

Note also that using if expressions to check for nil is uncommon, since there is a coalesce operator for that purpose which is more succinct and avoids double evaluation.

# Example 1 
print if(x>y, x, y) 

# Example 2 
print if(value, 'yes', 'no') # type is String 

# Example 3 
total += if(direction==DirectionEnum.Long, +1, -1) * amount 

# Example 4 
foo = if(condition, 'x', nil) # type is String? 

# Example 5 
foo = if(condition, 'x', 5) # type is Object