-
Notifications
You must be signed in to change notification settings - Fork 186
Optional usage
-
Avoid using
Optional#get()
. The only place where it is ok to use is in tests where you expect theOptional
to have a value and want the test to fail if it does not. -
If you need to transform the
Optional
to a concrete value you need to supply a fallback value in case theOptional
does not have a value. There are two options to do that. -
Optional#orElse(fallback value)
is suitable if you already have a fallback value or it is inexpensive to create one. -
Optional#orElseGet(function returning fallback value)
should be used if you don't have the fallback value yet and creating it is expensive (for example db lookup). The function you give it will only be called if theOptional
is empty so you avoid expensive computations if you don't need the fallback value. -
If you need to do some computation on the
Optional
value there are multiple ways to do that in a safe way. -
If the result of your computation is a new value (can be a different type the before) then you want to use
Optional#map
. You give it the function that takes the content of theOptional
and transforms it into a new value. The result of your computation will be wrapped up into a newOptional
. -
If your computation does not result in a new value and is only side-effecting then you should use
Optional#ifPresent
it is likemap
but does not result in a new value. -
If your computation results in a second
Optional
value you should useOptional#flatMap
. It is similar tomap
but function you give it returns a newOptional
which will be the overall result of theflatMap
.