dart-lang / dart-lang/language
Support nullableCallable?() for nullable/optional callbacks consistently to nullableCallable!()
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Currently, Dart only supports "force unwrap" calling of optional callables e.g.:
```dart
final VoidCallback? nullableCallback = (){};
...
nullableCallback!();
```
Replacing the exclamation mark by a question mark in the snippet above (producing `nullableCallback?();`) results in a compile-time error. Therefore, if we want the callback to execute only if it is not `null`, the code needs to read:
```dart
final VoidCallback? nullableCallback = condition ? (){} : null; // `condition` may or may not be true
...
if (nullableCallback != null) {
nullableCallback!();
}
```
I suggest supporting the `?` syntax in place of `!` with semantics "Only call the function/callable if it is not `null`", which would allow removing the `if` command and simplify the above code into:
```dart
final VoidCallback? nullableCallback = condition ? (){} : null; // condition may or may not be true
...
nullableCallback?();
```
In addition to being practical and more concise, this would make the force unwrap and optional chaining syntax more consistent throughout the language because calling a function/callable is currently the only place where question mark cannot be used in place of exclamation mark.
Also, this is a standard feature of most other null-safe languages.
Contributor guide
Research direction
No files or tests are named in the issue. Start by reviewing the nullable callable examples and the language specification's existing force-unwrap and optional-chaining rules. Done means the language design for nullable callable invocation is agreed and the corresponding specification and validation work is identified.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100