You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
Official description of Optional.flatMap:
If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional.
I personally felt that the descriptions are pretty cryptic and hard to understand, so much so that it was easier for me to understand by reading OpenJDK's source code. So I hope this ELI5 might be useful for others like me.
ELI5 description of Optional.map:
Let us have Optional<MyClass> myOp. myOp.map is meant to take in a function that does not return an Optional.
If there is a value inside the myOp, apply the function to the value.
Since we do not know if the result of the function will *chibabom or not, we wrap the result in an Optional for safety.
If there is no value inside the myOp, we return and empty Optional.
ELI5 description of Optional.flatMap:
Let us have Optional<MyClass> myOp. myOp.flatMap is meant to take in a function that already returns an Optional.
As a matter of fact, it will not compile if the mapper function does not return an Optional.
If there is a value inside the myOp, apply the function to the value.
Since we know that the function already returns an Optional, there is no fear that it will *chibabom.
Therefore wrapping the result in another Optional is redundant, and we can return it directly.
If there is no value inside the myOp, we return and empty Optional.
Description
Official description of Optional.map:
Official description of Optional.flatMap:
I personally felt that the descriptions are pretty cryptic and hard to understand, so much so that it was easier for me to understand by reading OpenJDK's source code. So I hope this ELI5 might be useful for others like me.
ELI5 description of Optional.map:
ELI5 description of Optional.flatMap:
*chibabom = explode, 爆炸, null value, invalid value, throw error
Topic:
Optional, Optional.map, Optional.flatMap
Screenshots (if any):
OpenJDK's Optional.map and Optional.flatMap source code:
Comic Representation:
The text was updated successfully, but these errors were encountered: