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

--

Coalesce Expression

The coalesce binary expression evaluates to the first non-nil value. There is an augmented assignment version of it as well.

Grammar

<a> ? <b>

The expression evaluates to a unless that value is nil, in which case, it evaluates to b.

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.

The type of the coalesce expression is the greatest common denominator between the type of a and the type of b.

Grammar

<a> ?= <b>

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.

# Example 1 
print name ? 'NONAME' 

# Example 2 
def foo(factor as decimal?) 
    factor ?= 1 # 'normalize' factor before proceeding with the rest of implementation 
    ...

# Example 3 
get name as String
    return _name ? .getType.name 

# Example 4 
# this: 
name = if(employee.manager.name<>nil, employee.manager.name, 'NONAME') 
# can evaluate the key expression twice and is less succinct than: 
name = employee.manager.name ? 'NONAME'