Modern Java in Action 5 - Optional
Optional

Contents
Null problem
Reasons why null is problematic:
- source of coding errors (missing checks)
- does not correctly model absence of value (null has no meaning)
- breaks Java philosophy of hiding pointers (null is a pointer which is NOT hidden)
Handling in other languages
- Groovy has safe navigation operator
- Kotlin is known for its null-safety
- Haskell has Maybe typeclass
- Scala also has an Option class
Optional
Creating
Three static methods may create instances of Optional:
- Optional.empty() - creates empty instance
- Optional.of(T) - returns Optional with given non-null value
- Optional.ofNullable(T) - returns either Optional with T value or Optional.empty() if value is null
java.util.Optional in Java 17 - compared to Java 8 - gains the following:
Version | Method | Desc |
---|---|---|
9 | ifPresentOrElse | if present, gives value to Consumetr<T> , else tuns given Runnable |
9 | or | returns Optional that will use alternative Optional that will be used if this one is empty |
9 | stream() | if value is present, returns a sequential Stream with single value or empty Stream |
10 | orElseThrow | if present, returns value, else, throws Exception provided by Supplier<? extends Exception> |
11 | isEmpty | returns true if value is present |
A chain of Optionals
In order to be able to navigate through a series of Optional values one needs to remember the difference between map
and flatmap
:
- if a mapping function returns value, you want to use
map
- if a mapping function returns Optional, you want to use
flatmap
Here, person’s car and car’s insurance are modelled as Optional values, hence the use of flatmap:
|
|
Ten wpis jest częścią serii modern-java-in-action.
- 2022-05-07 - Modern Java in Action 8 - concurrency and reactive programming
- 2022-02-07 - Modern Java in Action 7 - notes about the module system
- 2022-30-06 - Modern Java in Action 6 - Time and Date
- 2022-20-06 - Modern Java in Action 5 - Optional
- 2022-17-06 - Modern Java in Action 4 - refactoring and testing
- 2022-15-06 - Modern Java in Action 3 - collection API
- 2022-14-06 - Modern Java in Action 2 - fork-join and spliterators
- 2022-03-06 - Modern Java in Action 1 - Java 8 refresher