Understanding, Accepting and Leveraging Optional in Java
One of the most interesting features that Java 8 introduces to the language is the new Optional class. The main issue this class is intended to tackle is the infamous NullPointerException that every Java programmer knows only too well.
Essentially, this is a wrapper class that contains an optional value, meaning it can either contain an object or it can simply be empty.
Optional comes along with a strong move towards functional programming in Java and is meant to help in that paradigm, but definitely also outside of that.
Let's start with a simple use-case. Before Java 8, any number of operations involving accessing an object's methods or properties could result in a NullPointerException:
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
If we wanted to make sure we won't hit the exception in this short example, we would need to do explicit checks for every value before accessing it:
Read full article from Understanding, Accepting and Leveraging Optional in Java
No comments:
Post a Comment