Member-only story
Playing With Java Optional
A container object which may or may not contain a non-null value
Introduction
During your life as a Java developer, you have surely encountered a NullPointerException
. Read on if this is the exception you encounter the most. I imagine you might be thinking something like, “Yes, I agree, NullPointerExceptions is a pain for any Java developer, novice or expert, but there’s not much we can do about them.“ This is a common feeling in the programming world. Until Java 8 introduced Optional
.
Optional
allows an object to wrap those nullable values. The intention is to finally give us the ability to express a type for the returned value more clearly.
Instead of using a Java annotation, which is not checked at compile-time, Optional allows you to boost your methods and indicate that your method probably returns “empty” (and not null) values.
The NullPointerException problem
Before diving into the usage of Optional, let’s understand what issue it promises to resolve. When we create a java application, we will surely use method chaining to de-reference object properties, which can…