Skip to content

Instantly share code, notes, and snippets.

Created December 9, 2016 19:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
public interface CoalescingCallback<U> {
U call();
* See documentation for coalesce(CoalescingCallback<T>, T)
public static <T> T coalesce(CoalescingCallback<T> expression) {
return coalesce(expression, null);
* Null coalescing operator for Java. Not a real operator because custom operators are not allowed.
* Together with lambda expressions, this allows compact null coalescing in java, meaning
* coalesce(() -> would return null if any part of it is null. This avoids
* a) cumbersome try-catch blocks or b) equally cumbersome if-else statements
* @param expression The expression to be evaluated.
* @param defaultValue Default value
* @param <T> Return type
* @return The expected value of the expression, or null
public static <T> T coalesce(CoalescingCallback<T> expression, T defaultValue) {
try {
T result =;
return result;
} catch (NullPointerException e) {
return defaultValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment