Null-aware function call? [duplicate]
Asked Answered
H

1

7

Dart has some null-aware operators, i.e. it is possible to do

var obj;
obj?.foo(); // foo is only called if obj != null.

Is this also possible for functions that are stored or passed to variables? The usual pattern is

typedef void SomeFunc();

void foo(SomeFunc f) {
  if (f != null) f();
}

It would be nice to have some null-aware calling here, like f?(). Is there anything we can use to not litter the code with null checks for those callbacks?

Hills answered 28/2, 2019 at 19:43 Comment(0)
R
17

Form the docs:

Dart is a true object-oriented language, so even functions are objects and have a type, Function.

Apply the null aware ?. operator to the call method of function objects:

typedef void SomeFunc();

SomeFunc f = null;

f?.call();
Radiomicrometer answered 28/2, 2019 at 20:20 Comment(2)
Thank you, this indeed works. From the docs alone, this wasn't clear to me (the "call()" is mentioned only for callable classes. But put together, it makes sense.Hills
You can also use apply for this for more control : See https://mcmap.net/q/175648/-null-aware-function-invocation-operatorTraumatism

© 2022 - 2024 — McMap. All rights reserved.