2 ms·
One advantage of Optional is allowing you to remove null from the language and then stop worrying about null checks. But you can't get that in Java, because you
by lmm 4y ago
One advantage of Optional is allowing you to remove null from the language and then stop worrying about null checks. But you can't get that in Java, because you can't remove null from the language. So in practice that benefit is very small - you still have to worry about null in Java code, and will for decades.
The other advantage of Optional is that it behaves consistently regardless of what's inside it, which means you can use it in generic code in a way that you can't use null. For example a common problem with null in Java is that if you call map.get(key) and the result is null, you can't tell whether that means the key isn't present in the map, or the key is present but the value is null. Whereas if you're using optionals, you can distinguish between None (key not present) and Some(None) (key is present, but mapped to None).
So Java could have added a getOptional method to Map (with a default impl), and then if getOptional(key) returns None the key isn't present, if it returns Some(null) then the key is present but mapped to null. That would be a legitimate, immediate use case, that would give people a benefit from switching to Optional today, and would start the ball rolling on using optionals, and maybe eventually in a few decades they would be widespread enough that we could start deprecating null in the language.
But instead they made it so you can't put null in Optional from day 1. Which would be great if there was a way to instantly migrate everything, but it makes it harder to start using Optional in an existing codebase and reduces the short-term benefits, for the sake of a future that (because of that very lack of short-term benefits) will never come.