LYR-SEM0062
'?.' calling a field that holds a function
a?.f() is written where f is a field of function type, not a method.
Explanation
?. with a call works on a method: when the receiver is absent the call does not happen and the result is null. On a field that holds a function value the form would ask two questions (is the receiver there, is the field set) with one ?, and the language has no ?().
Read the field with ?. into a variable first, test it, then call it.
Wrong
struct Handler {
run: fn() -> int,
}
fn main(): void {
let h: ?Handler = Handler { run = (): int => 1 };
let _ = h?.run();
}
Right
struct Handler {
run: fn() -> int,
}
fn main(): void {
let h: ?Handler = Handler { run = (): int => 1 };
let run = h?.run;
if (run != null) {
let _ = run();
}
}