Created
May 1, 2026 19:37
-
-
Save kamack38/30a5245e33cc26ac540872e4896f8725 to your computer and use it in GitHub Desktop.
Java result. Source: https://x.com/ptr_to_joel/status/1955055394725958101
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
| sealed interface Result<T> { | |
| record Ok<T>(T value) implements Result<T> {}; | |
| record Err<T>(Throwable err) implements Result<T> {}; | |
| static <T> Result<T> of (Callable<T> code) { | |
| try { | |
| return new Ok<T>(code.call()); | |
| } catch (Throwable throwable) { | |
| return new Err<T>(throwable); | |
| } | |
| } | |
| default <R> Result<R> map(Function<T, R> mapper) { | |
| return switch (this) { | |
| case Ok<T> ok -> Result.of(() -> mapper.apply(ok.value())); | |
| case Err<T> err -> new Err<R>(err.err()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment