Last active
March 3, 2023 09:22
-
-
Save cboudereau/d333d7613b70ee1456e944e2d19f984d to your computer and use it in GitHub Desktop.
This file contains 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
package com.accorlight; | |
import java.util.function.Function; | |
public final class Result<R, E> { | |
final R value; | |
final E error; | |
public static class ResultException extends RuntimeException { | |
public ResultException(final String message) { | |
super(message); | |
} | |
} | |
private Result(final R value, final E error) { | |
this.value = value; | |
this.error = error; | |
} | |
private final boolean isOk() { | |
return this.error == null; | |
} | |
private final boolean isError() { | |
return !isOk(); | |
} | |
public final R get() { | |
if (isOk()) { | |
return value; | |
} | |
throw new ResultException("Expected an ok result but got an error"); | |
} | |
public final E getError() { | |
if (isError()) { | |
return error; | |
} | |
throw new ResultException("Expected an error but got an ok result"); | |
} | |
public static final <R, E> Result<R, E> ok(R value) { | |
return new Result<>(value, null); | |
} | |
public static final <R, E> Result<R, E> error(E error) { | |
return new Result<>(null, error); | |
} | |
public final <T> Result<T, E> map(Function<R, T> f) { | |
return this.isOk() ? ok(f.apply(this.value)) : error(this.error); | |
} | |
public final <T> Result<T, E> bind(Function<R, Result<T, E>> f) { | |
return this.isOk() ? f.apply(this.value) : error(this.error); | |
} | |
public final <T> Result<R, T> mapError(Function<E, T> f) { | |
return this.isError() ? error(f.apply(this.error)) : ok(this.value); | |
} | |
public static final <T> T merge(Result<T, T> r) { | |
return r.isOk() ? r.value : r.error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment