Created
March 6, 2025 06:06
-
-
Save Hogeyama/2c2d369370e051597f70436ba5a0edcc 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
| /** | |
| * Example: | |
| * | |
| * ```java | |
| * withEarlyReturn(Result.class, (c) -> { | |
| * var value = switch (someAction()) { | |
| * case Success(var value) -> { | |
| * return value; | |
| * } | |
| * case Failure(var error) -> { | |
| * throw c.earlyReturn(error); | |
| * } | |
| * } | |
| * ... | |
| * }) | |
| * ``` | |
| * | |
| * ```java | |
| * var resetRequest = | |
| * userRepository | |
| * .findByEmail(email) | |
| * .orElseThrow(() -> c.earlyReturn(new UserNotFound())); | |
| * ``` | |
| */ | |
| public class EarlyReturn { | |
| @SuppressWarnings("unchecked") | |
| public static <T> T withEarlyReturn(Class<T> clazz, EarlyReturnBlock<T> block) { | |
| try { | |
| return block.run(new EarlyReturnController()); | |
| } catch (EarlyReturnException e) { | |
| if (clazz.isInstance(e.value)) { | |
| return (T) e.value; | |
| } else { | |
| // for nested withEarlyReturn | |
| throw e; | |
| } | |
| } | |
| } | |
| @FunctionalInterface | |
| public interface EarlyReturnBlock<T> { | |
| T run(EarlyReturnController k); | |
| } | |
| public static class EarlyReturnException extends RuntimeException { | |
| Object value; | |
| private EarlyReturnException(Object value) { | |
| this.value = value; | |
| } | |
| } | |
| public static class EarlyReturnController { | |
| public <T> EarlyReturnException earlyReturn(T value) { | |
| throw new EarlyReturnException(value); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment