| 1 | The '''coalesce''' binary expression evaluates to the first non-nil value. There is an augmented assignment version of it as well. |
| 2 | |
| 3 | === Grammar === |
| 4 | {{{ |
| 5 | <a> ? <b> |
| 6 | }}} |
| 7 | |
| 8 | The expression evaluates to a unless that value is '''nil''', in which case, it evaluates to '''b'''. |
| 9 | |
| 10 | Although uncommon, nothing prevents b itself from also being '''nil'''. Neither expression will be evaluated more than once and if a is non-nil then b will not be evaluated at all. |
| 11 | |
| 12 | The type of the coalesce expression is the greatest common denominator between the type of '''a''' and the type of '''b'''. |
| 13 | |
| 14 | === Grammar === |
| 15 | {{{ |
| 16 | <a> ?= <b> |
| 17 | }}} |
| 18 | |
| 19 | In the augmented assignment version, the result is assigned back to a. This requires that b is type compatible with a or a compilation error will occur. |
| 20 | |
| 21 | {{{ |
| 22 | #!cobra |
| 23 | # Example 1 |
| 24 | print name ? 'NONAME' |
| 25 | |
| 26 | # Example 2 |
| 27 | def foo(factor as decimal?) |
| 28 | factor ?= 1 # 'normalize' factor before proceeding with the rest of implementation |
| 29 | ... |
| 30 | |
| 31 | # Example 3 |
| 32 | get name as String |
| 33 | return _name ? .getType.name |
| 34 | |
| 35 | # Example 4 |
| 36 | # this: |
| 37 | name = if(employee.manager.name<>nil, employee.manager.name, 'NONAME') |
| 38 | # can evaluate the key expression twice and is less succinct than: |
| 39 | name = employee.manager.name ? 'NONAME' |
| 40 | }}} |