The difference I see is, when you work with a nullable type, each function has to do the check
so
const add3 = (val) => val ? val + 3 : null;
const multiplyBy10 = (val) => val ? val * 10 : null
So the argument type goes from being
val
to
val?
where the calling code doesn't necessarily have type safety since this argument is now optional (it can be a number or null and either is acceptable) instead of the following (with no conditionals or ternaries)
const add3 = val => val + 3;
const multiplyBy10 = val => val * 10;
This is possible cause
optional.map
implicitly handles the case where the data is missing by default, its built into the data type and the code you write doesn't need to worry about it. Its the responsibility of the Optional object.
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.
That is where you use optional chaining + extension method. And that is basically identical to Optional.map or whatever method in those language with Optional type
in kotlin
func add3 (val: Int?) = val ?.let { it + 3 }
The language gives you a way to say: `this value plus 3 if it exist or just return null`
Unfortunately, there is no such method in js currently, so it looks half baked.
Ah, I gotcha, and I had already read another of your comments below. Yep, agree that is nicer in these cases. I still agree with the author that they made the right choice for Dart.
Maybe they didn't mention it because both approaches can do that, or maybe I'm misunderstanding?