"The last flaw with Java's implementation is a bit ironic — It's possible for the optional reference itself to be null."
ouch.
11–20 of 197 posts
"The last flaw with Java's implementation is a bit ironic — It's possible for the optional reference itself to be null."
ouch.
TL;DR You can call `Optional.get()` to deliberately circumvent the safety mechanisms of Optional. The author apparently concludes that since it does not solve ALL error cases it does not solve ANY error cases...
The problem is that you don't get guarantees that something is not null; you can still do Optional myOptional = null. Second, you're not required to handle the not-present case. Third, if you attempt to get the value of an optional (using .get()) when it is not present, you get an (unchecked, so no requirement to catch) exception - basically replacing NullPointerException with NoSuchElementException. The only value O…
Optional is planned to become a value type.
Previous discussion on reddit: https://www.reddit.com/r/programming/comments/3pl7o0/java_8s...
tl;dr: use map, orElseGet, orElse
"Comparing Optionals and Null in Swift, Scala, Ceylon and Kotlin"
http://codemonkeyism.com/comparing-optionals-and-null-in-swi...
May be name "get()" is too short and innocent-looking.
Using get() is just bad style and so is returning null where you could return Collections.emptyList(). Previous discussion on reddit: https://www.reddit.com/r/programming/comments/3pl7o0/java_8s... tl;dr: use map, orElseGet, orElse
You shouldn't replace:
if(x == null)
{
y = x.doSomething();
}
with if(optionalX.isPresent())
{
y = x.doSomething();
}
You should replace it with: y = Optional.ofNullable(x)
.map(ClassX::doSomething)
.orElse(null);The lack of pattern matching doesn't make it useless. The existence of Optional reminds the programmer to check whether the value is present, and the type system does enforce this; you can't accidentally treat an Optional as a reference of the same type. The type system does help us remember to handle things; it is a reminder enforced by the type system that's easy to examine during code review. Yes, you can write ge…
Shameless self plug "Comparing Optionals and Null in Swift, Scala, Ceylon and Kotlin" http://codemonkeyism.com/comparing-optionals-and-null-in-swi...