Created
December 9, 2016 19:46
-
-
Save brightredchilli/14fbdb134ff4adc2abf7149b40809964 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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