-
Notifications
You must be signed in to change notification settings - Fork 225
Optional usage
-
Avoid using
Optional#get(). The only place where it is ok to use is in tests where you expect theOptionalto have a value and want the test to fail if it does not. -
If you need to transform the
Optionalto a concrete value you need to supply a fallback value in case theOptionaldoes 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 theOptionalis empty so you avoid expensive computations if you don't need the fallback value. -
If you need to do some computation on the
Optionalvalue 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 theOptionaland 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#ifPresentit is likemapbut does not result in a new value. -
If your computation results in a second
Optionalvalue you should useOptional#flatMap. It is similar tomapbut function you give it returns a newOptionalwhich will be the overall result of theflatMap.