15 ms·
You could define operations on nullable types to allow this in Dart, like: extension NullableNumExtensions on num? { num? operator +(num? other) {
by munificent 6y ago
You could define operations on nullable types to allow this in Dart, like:
extension NullableNumExtensions on num? {
num? operator +(num? other) {
if (this != null && other != null) return this + other;
return null;
}
}
main() {
num? i, j;
print(i + j);
}
For method calls, we have a null-safe method call syntax that automatically lifts the operation to give you a nullable result:
int? i;
var b = i?.isEven; // b has type null?
We could have made all operations implicitly do this lifting, but our experience is that this isn't what users want. They want to know as early in their code when an operation on a potentially-absent value is attempted and reconcile right there what behavior they want.