Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active January 15, 2017 17:19
Show Gist options
  • Save gaplo917/91e0d4e4bce128a31bc16132b7e5babf to your computer and use it in GitHub Desktop.
Save gaplo917/91e0d4e4bce128a31bc16132b7e5babf to your computer and use it in GitHub Desktop.
Java Optional overhead
// Java
// Optional Type Overhead
Optional<String> strOpt = null; // Compile OK
Optional<String> strOpt = Optional.empty(); // Compile OK
strOpt = null; // Compile OK
strOpt == null; // Compile OK => true
strOpt = Optional.of("gary"); // Compile OK
strOpt = Optional.ofNullable("gary"); // Compile OK
// cannot direct assign a value
strOpt = "gary"; // Compile error: Type mismatch
// cannot direct compare with a value
strOpt.equal("gary"); // Compile error: Type mismatch
strOpt.equal(Optional.of("gary")); // Compile OK, true
// unwrap and compare the wrapped value
if(strOpt.isPresent()){
final String str = strOpt.get();
return str.equal("gary");
}
else {
return false
}
// do something when the wrapped value is not null
strOpt.ifPresent(str -> {
doSth(str)
});
// Easy to be mis-used
// in some case,
// null is a good representation of nothing instead of empty String
String str = strOpt.orElse("");
// throw NullPointerException if the wrapped value is null
String str = strOpt.get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment