Version 2 (modified by todd.a, 7 years ago)


If Expression

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


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.

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

Note 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