What You Might Not Know About Optional
How Optional can help you remove the nasty null pointer errors
Published in
4 min readAug 19, 2021
· What’s the correct usage of ofNullable?
· Don’t return null, use Optional
· Why is Optional#of necessary?
· Why Optional#of throws NullPointerException?
· You shouldn’t use Optional for method arguments
What’s the correct usage of ofNullable?
How did you represent absent values before Optional
? Yes, you used null
. The code would look something like this:
The problem Optional
solves is the absence of value. Look at the following example.
The first line will cause NullPointerException
on the caller. Line using Optional
on the contrary won’t. You need to unwrap the Optional
and handle the absence.