What are the coalescing operators in EK9?
← Operators and Expressions · Ref: Q899
EK9 has coalescing COMPARISON operators that return a value while handling UNSET gracefully. These are unique to EK9.
?? and ?: — VALUE COALESCING
Returns the left value if SET, otherwise the right:
result <- maybeValue ?? defaultValue result <- maybeValue ?: fallback
COALESCING COMPARATORS (unique to EK9)
These COMPARE two values and RETURN a result. If either is UNSET, return the SET one:
<? — coalescing minimum: returns the SMALLER value >? — coalescing maximum: returns the LARGER value <=? — coalescing less-or-equal minimum >=? — coalescing greater-or-equal maximum
Examples:
bestPrice <- price1 <? price2 returns the cheaper price topScore <- score1 >? score2 returns the higher score
All coalescing operators RETURN a value — use them on the RIGHT side of <-.
NOTE: :=? is NOT a coalescing operator. It is an ASSIGNMENT operator (see Q1152). :=? assigns a value only if the target is unset. Do not confuse :=? (assignment) with <? (comparison).
See Q24 for tri-state semantics. See Q898 for the ? operator. See Q1226 for <? vs :=? contrast.
Example
defines module qa.operators.coalescingdetail defines function <?- Shows ?? value coalescing. Like Kotlin's ?: or JavaScript's ?? -?> getDisplayName() as pure -> userName as String defaultName as String <- rtn as String: userName ?? defaultName <?- Shows <? coalescing minimum. Unique to EK9 — returns smaller, or the SET one. -?> cheaperPrice() as pure -> priceA as Float priceB as Float <- rtn as Float: priceA <? priceB <?- Shows >? coalescing maximum. Unique to EK9 — returns larger, or the SET one. -?> higherScore() as pure -> scoreA as Integer scoreB as Integer <- rtn as Integer: scoreA >? scoreB defines program CoalescingDemo() stdout <- Stdout() // ?? value coalescing — like Kotlin's ?: or JS's ?? userName <- String() displayName <- getDisplayName(userName, "Guest") stdout.println(`Display: ${displayName}`) setName <- "Alice" displayName2 <- getDisplayName(setName, "Guest") stdout.println(`Display: ${displayName2}`) // <? coalescing minimum — RETURNS a value cheapest <- cheaperPrice(29.99, 19.99) stdout.println(`Cheapest: ${cheapest}`) // >? coalescing maximum topScore <- higherScore(85, 92) stdout.println(`Top: ${topScore}`)
Other ways to ask this
- How do coalescing comparators work in EK9?
- What do <? and >? mean in EK9?
- What is the ?? operator in EK9?
- How does null coalescing work in EK9?
Coming from another language?
Kotlin: ?: elvis operator — similar to EK9's ??. JavaScript: ?? nullish coalescing — similar to EK9's ??. Swift: ?? nil coalescing — similar to EK9's ??. C#: ?? null coalescing — similar to EK9's ??. None of these languages have coalescing COMPARATORS (<?, >?, <=?, >=?) — these are unique to EK9.
Keywords: null, comparator, coalescing, maximum, minimum, unset, elvis, coalesce