> You can map, filter, reduce, chain, compose functions that all work with optionals
Maybe they didn't mention it because both approaches can do that, or maybe I'm misunderstanding?
Maybe they didn't mention it because both approaches can do that, or maybe I'm misunderstanding?
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. 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.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.