Type: Code Smell
The following Code snippets makes use of an unnecessary ‘Optional.flatMap()’ call. There should never be a reason to manually wrap a mapping operation into a Optional type.
Noncompliant Code:
// (1)
Optional.of(2)
.flatMap(value -> Optional.of(1));
// (2)
Optional.ofNullable(2)
.flatMap(value -> Optional.ofNullable(1));
Compliant Code:
// (1)
Optional.of(2)
.map(value -> 1);
// (2)
Optional.ofNullable(2)
.map(value -> 1);
Note that in case of (1) the compliant code actually changes the behaviour since Optional.of()
would throw an exception if a null value is provided, while Optional.map()
would return an empty Optional. Therefore it might require more user-interaction.
Case (2) should be always compliant.
Also see the following request on IntelliJ IDEA:
https://youtrack.jetbrains.com/issue/IDEA-236581/Inspection-to-simplify-Optional.flatMap