??
a ?? b yields a, unless a is null; then it evaluates b and yields that.
Details
??short-circuits: the right side runs only when the left side isnull.- The left side must have a type that includes
null. On any other type,??is a compile error. - The right side may be any expression, including
return,break, andpanic(...). Afterlet v = x ?? return ...,vis not nullable. ??binds looser than arithmetic, comparison, and equality, and tighter than|. It cannot be mixed with&&,||, a comparison, an equality test, or a pipe stage without parentheses.
Basic examples
A fallback for a nullable value:
let nickname: string | null = null
nickname ?? "anonymous" // "anonymous"
let name: string | null = "Ann"
name ?? "anonymous" // "Ann"A default for a missing map key:
let ages = Map{ "Ann": 31, "Bob": 27 }
ages["Ann"] ?? 0 // 31
ages["Cy"] ?? 0 // 0Scope
Chains
?? chains: the first value that is not null wins.
let flag: string | null = null
let env: string | null = "staging"
flag ?? env ?? "production" // "staging"A nullable right side
When the right side can be null too, so can the result:
let primary: string | null = null
let backup: string | null = null
primary ?? backup // null
(primary ?? backup) ?? "localhost" // "localhost"After ?.
?. turns a missing link into null, and ?? replaces it:
type Address = { city: string }
type User = { name: string, address: Address | null }
let ann = User{ name: "Ann", address: Address{ city: "Oslo" } }
let bob = User{ name: "Bob", address: null }
ann.address?.city ?? "unknown" // "Oslo"
bob.address?.city ?? "unknown" // "unknown"Empty collections and numbers
Without an expected type, the right side takes the left side's type without null, so an empty literal needs no annotation:
let groups = Map{ 1: [10, 20] }
groups[1] ?? [] // [10, 20]
groups[2] ?? [] // []Array.sum, Array.min, and Array.max return null for an empty array; ?? gives the zero:
let empty: Array[float64] = []
[1.5, 2.0].sum() ?? 0.0 // 3.5
empty.sum() ?? 0.0 // 0.0return, break, and panic
A right side of type never leaves instead of producing a value. The name on the left is then not nullable:
func tens(xs: Array[int]): int {
let first = xs.first() ?? return -1
first * 10
}
println(tens([4, 5]))
println(tens([]))40
-1?? break ends a loop when a closed channel gives null:
let jobs: Channel[string] = Channel.new(2)
jobs.send("build")
jobs.send("test")
jobs.close()
while true {
let job = jobs.receive() ?? break
println("running ${job}")
}running build
running test?? panic(...) unwraps a value that must be there:
let port: int | null = null
let p = port ?? panic("no port configured") // panic: no port configuredShort-circuit
The right side does not run when the left side has a value:
func fallback(): string {
println("fallback ran")
"default"
}
let set: string | null = "set"
let unset: string | null = null
println(set ?? fallback())
println(unset ?? fallback())set
fallback ran
defaultApplications
Counting with a map
Start a missing count at zero:
let words = "the cat and the hat".split(" ")
let counts: Map[string, int] = Map{}
for w in words {
counts[w] = (counts[w] ?? 0) + 1
}
println(counts["the"])
println(counts["dog"] ?? 0)2
0Failing early with a Result
Turn a missing value into an error and return it:
type Account = { id: string, balance: int }
func balance(accounts: Map[string, Account], id: string): Result[int, Error] {
let account = accounts[id] ?? return Result.fail("no account ${id}")
Result.ok(account.balance)
}
let accounts = Map{ "a1": Account{ id: "a1", balance: 50 } }
println(balance(accounts, "a1"))
println(balance(accounts, "b2"))Ok{ value: 50 }
Err{ error: Error{ message: "no account b2" } }Optional settings
Fill in defaults for the fields a user left out:
type Settings = { host: string | null = null, port: int | null = null }
func address(s: Settings): string {
"${s.host ?? "localhost"}:${s.port ?? 8080}"
}
println(address(Settings{}))
println(address(Settings{ port: 9000 }))localhost:8080
localhost:9000Properties and relations
a ?? b is the if expression that tests a against null:
let values: Array[int | null] = [3, null]
for a in values {
assert((a ?? 0) == (if a != null { a } else { 0 }))
}Possible issues
A left side that cannot be null
let name = "Ann"
let shown = name ?? "anonymous" // error: ?? needs a nullable left side, got stringA stored null and a missing key give the same result
?? cannot tell them apart. Ask the map with has when the difference matters:
let theme = Map{ "dark": null, "light": "#fff" }
theme["dark"] ?? "none" // "none"
theme["sepia"] ?? "none" // "none"
theme.has("dark") // true
theme.has("sepia") // falseMixing with a comparison
?? binds looser than a comparison, so n ?? 0 > 5 would read as n ?? (0 > 5). Without parentheses, the mix is a compile error:
let n: int | null = 3
let big = n ?? 0 > 5 // error: '??' cannot mix with '>' without parenthesesParenthesize the ??:
let n: int | null = 3
(n ?? 0) > 5 // falseMixing with && and ||
let ready: bool | null = null
let start = ready ?? false && true // error: '??' cannot mix with '&&' or '||' without parenthesesMixing with a pipe
| binds looser than ??, so a fallback after a pipeline needs parentheses:
let xs = [1, 2, 3]
let total = xs | Array.sum() ?? 0 // error: '|' binds looser than '??', so parenthesize the pipe, as in (a | f()) ?? bParenthesize the pipe:
let xs = [1, 2, 3]
(xs | Array.sum()) ?? 0 // 6return takes everything to its right
x ?? return a + b returns a + b, not a. A plain ?? return 0 ends at the line:
func double(x: int | null): int {
let v = x ?? return 0
v * 2
}
println(double(4))
println(double(null))8
0To end the return earlier, parenthesize it.
A nullable fallback keeps the result nullable
let a: string | null = null
let b: string = a ?? null // error: cannot use null where string is expected