If you just want to provide a hint to the caller at compile time about whether you intend for the possibility of returning null, you could use @Nullable/@NotNull annotations to achieve that with no overhead.
E.g. you might want to return the streetnumber of a user's address. When a NPE is thrown, was it because there is a bug somewhere in the code or because the user's address has no street number?
With Optional, it is clear: there was no street number.
case class Address(street: String, city: String, state, String) case class User(id: Int, name: String, address: Option[Address])
def filterCAUsers(users: List[User]): List[User] = users.filter(_.address.exists(_.state != "CA"))
I kind of think that sentence is contrary to the point of Optional, and if you start from that mindset then Optionals do end up no better than nulls.
Instead you enforce good hygiene where you unwrap early and pass non-Optionals for anything that you "know" is non-null. If you call a function which returns optional, and you're find yourself thinking "nah, I _know_ this is definietly non-empty" then you're incorrect; the API explicitly is telling you that it definitely can be empty.
If you just do "Map.get(x)" and you get null because your thinking was wrong, then the NPE will pop up potentially 10 layers later or an hour later, when the null-value was tried to be used in your program.
On the other hand, with "Map.get(x).orElseThrow()" you will have an exception thrown immediately! Even better, you should customize that as "Map.get(x).orElseThrow(NoSuchElementException(x))" so that you know the value that was unexpectedly not in the list.
That will make debugging much easier and will potentially fail a test case while a "Map.get(x)" might not cause the test to fail.
so we put on our big-dev pants and build all sorts of structures around handling errors to make it more sound/ergonomic.
but at the end of the day:
o its still very difficult to respond in a semantically meaningful way to errors as code
o they still almost always just get dumped into a log or ignored, or just result in a panic
o even if we have managed to surface them - they still aren't really that actionable by the end user
so we haven't helped the situation much, but some of these answer like catch/throw have really unpleasant consequences - we may have made it worseScala's ZIO is one of the better examples if you are interested to look into an alternative.
> Every NullPointerExceptipn my code ever caused was good, because it helped find an error state that had no acceptable default non error state alternative.
Yeah, and with Optional you would have found it at compile-time.