language
language copied to clipboard
New Operator: ?.() conditional function call
Dart supports two conditional access mecanisms
Dart
foo?.bar // member
fooList?[1] // subscript
There is a third conditional access mecanism for conditional functions calls, currently available on javascript from MDN
You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.
Javascript
foo?.prop // member
fooList?.[expr] // subscript
// ↓↓↓↓
func?.(args) // function
That was considered, actually as maybeFun?(args)
, when Dart introduced ?[...]
for null aware indexing.
It wasn't added, one reason being that it parses badly, another that maybeFun?.call(arga)
is an adequate workaround.
Allowing a null-aware function call as maybeFun?.(args)
is an option that has been considered as well.
It's just that ?.call
is still a perfectly adequate alternative, so it's never been urgent to shorten that.
(And maybe we'd want the syntax for something else.)