Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.Optional;
import java.util.function.Function;
class Main {
public static void main(String[] args) {
Optional<String> o = Optional.of("foo");
Function<String, String> f = s -> null;
Function<String, String> g = String::valueOf;
//lawless lolz
System.out.println( o.map(g.compose(f)) ); //Optional[null]
System.out.println( o.map(f).map(g) ); //Optional.empty
//This is because
System.out.println( o.map(f) ); //Optional.empty
//Once again for clarity
System.out.println( o.map(s -> null) ); //Optional.empty
//And now for more lolz
System.out.println( o.flatMap(s -> null) ); //throws NullPointerException
}
}
@jroper

This comment has been minimized.

Copy link

commented Apr 20, 2016

Just for clarity, the result of line 11 is an Optional of the String "null", not an Optional of null.

@jedws

This comment has been minimized.

Copy link

commented Apr 21, 2016

just for clarity?

@oxbowlakes

This comment has been minimized.

Copy link
Owner Author

commented Apr 22, 2016

That's correct. Optional has been designed to explicitly never be able to contain a null value. Arguably more correct behaviour would have been to have map to throw an NPE if the function application returned null - but you'd still have the issue that o map f map g and o map (g compose f) would be different.

Presumably one "advantage" for explicitly disallowing Optional(null) might raise its head when the JVM gets value classes.

@tonymorris

This comment has been minimized.

Copy link

commented Apr 24, 2017

FWIW, we tried this (failed) experiment about 12 years ago. The correct solution is to assume that null does not exist, at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.