Skip to content

Instantly share code, notes, and snippets.

@Hogeyama
Created March 6, 2025 06:06
Show Gist options
  • Select an option

  • Save Hogeyama/2c2d369370e051597f70436ba5a0edcc to your computer and use it in GitHub Desktop.

Select an option

Save Hogeyama/2c2d369370e051597f70436ba5a0edcc to your computer and use it in GitHub Desktop.
/**
* 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