Skip to content

Instantly share code, notes, and snippets.

Embed
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(() -> 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