In this post, we will see about Java 8 optional.
Did you ever get NullPointerException as Java developer? If you are experienced Java developer, y...
For further actions, you may consider blocking this person and/or reporting abuse
Yes, optional is a great pattern. Have you tried Kotlin, Swift, or TypeScript which have the choice of non-nullable references? It’s a much more effective way of eliminating null references. That being said, I still use Optional or Either pattern in TypeScript when I want to return one of two types. I’m glad to find another fan of this defensive programming technique. :)
It is worth mentioning that Optional has seen some improvements in versions after Java 8 and it is now much more interesting to use.
The new methods ifPresentOrElse(), or(), orElseThrow(), isEmpty(), map(), flatMap()...
Now we are talking! :D
Cheers!
great article, but I have a little confused about this. when you check optional is present, in this case, I can check this is null or not ... why don't do that? cuz looks quite the same.
Optional force us to check the presence to avoid human error.
Good question and excellent answer! Thank you!
using of( ) will throw exception?
Yes, Optional.of will throw an Exception if you pass a null value. If you cannot be sure that the value will not be null, then use Optional.ofNullable(..,);
One just has to wonder why they did not make it the default behaviour with the short name.
¯_(ツ)_/¯
I think one of the best features introduced in Java 8 was Optional. However, in my opinion, it can sometimes be a little confusing.
Yes I feel the same. It’s like you need to know when to use it. What are the cases it’s good for. You might want to explore using it with map() it’s a powerful tool.
Excellent Blog very imperative good content
Core Java Training in KPHB
Thanks for sharing!