Skip to content

Instantly share code, notes, and snippets.

@brightredchilli
Created December 9, 2016 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brightredchilli/14fbdb134ff4adc2abf7149b40809964 to your computer and use it in GitHub Desktop.
Save brightredchilli/14fbdb134ff4adc2abf7149b40809964 to your computer and use it in GitHub Desktop.
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(() -> foo.bar().toString()) 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 = expression.call();
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