| 1 | The '''if''' expression evaluates to exactly one of two expressions based on a condition. |
| 2 | |
| 3 | === Grammar === |
| 4 | {{{ |
| 5 | if(<condition>, <texpr>, <fexpr>) |
| 6 | }}} |
| 7 | |
| 8 | 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. |
| 9 | |
| 10 | The type of the '''if''' expression is the greatest common denominator between the type of '''texpr''' and the type of '''fexpr'''. |
| 11 | |
| 12 | 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. |
| 13 | |
| 14 | {{{ |
| 15 | #!cobra |
| 16 | # Example 1 |
| 17 | print if(x>y, x, y) |
| 18 | |
| 19 | # Example 2 |
| 20 | print if(value, 'yes', 'no') # type is String |
| 21 | |
| 22 | # Example 3 |
| 23 | total += if(direction==DirectionEnum.Long, +1, -1) * amount |
| 24 | |
| 25 | # Example 4 |
| 26 | foo = if(condition, 'x', nil) # type is String? |
| 27 | |
| 28 | # Example 5 |
| 29 | foo = if(condition, 'x', 5) # type is Object |
| 30 | }}} |