That with the lambdas makes for a very powerful new set of features in Java 8. It’s almost a new language.
I played with this today and found it a little awkward. ML-like languages can get rid of NULL because they have pattern matching. In fact, I couldn’t even get it to work. Something as simple as:
// class field
public Optional<Character> gender;
return " gender=" + gender.orElse('U');
The point being to return M/F (or whatever other character is set as gender) .. this still returns a null pointer exception, if gender is uninitialized. To initialize it one has to do:
public Optional<Character> gender = Optional.of('U');
Which really defeats the purpose of using Optional (i.e. to avoid NPEs). I have no control over client code.
Am I wrong? Am I misunderstanding the expected behaviour?
That is the expected behavior. Java 8 doesn’t enforce non-nullable references, neither does Scala. Optional is just a design pattern.
There are other languages, like Kotlin, which have language level support for non-nullable types.
yes (it’s expected behaviour and it defeats the purpose); it seems like the groovy / c# approach is more pragmatic (i think the elvis operator would do fine here?).
it seems like a language extension (.?) would be better than a clunky library class here.
I think to initialize the field you only need this:
public Optional<Character> gender = Optional.empty();
which is a little better – you don’t need to think of or define a custom value for “unknown”.
And as others have said, yes, you still have to work around the fact that Java cannot guarantee that an object reference is not null. An API’s use of Optional signals that since the API uses it where possible, it probably won’t ever return a plain null, so you don’t have to bother checking for NPEs from it. But you can still never be sure that you won’t get null – the latest Java hasn’t changed that property of object references.