Last active
October 31, 2020 20:17
-
-
Save dam5s/89faf9818e234c8081b881efb4fb61ab to your computer and use it in GitHub Desktop.
Result type for Java codebases, if you don't get to use Kotlin.
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
import java.util.function.Function; | |
interface Result<T, E> { | |
static <T, E> Success<T, E> success(T value) { | |
return new Success<>(value); | |
} | |
static <T, E> Error<T, E> error(E value) { | |
return new Error<>(value); | |
} | |
<U> Result<U, E> map(Function<T, U> mapping); | |
<F> Result<T, F> mapError(Function<E, F> mapping); | |
<U> Result<U, E> flatMap(Function<T, Result<U, E>> mapping); | |
<F> Result<T, F> flatMapError(Function<E, Result<T, F>> mapping); | |
T orElse(T ifError); | |
T orElse(Function<E, T> ifError); | |
class Success<T, E> implements Result<T, E> { | |
private final T value; | |
private Success(T value) { | |
this.value = value; | |
} | |
@Override | |
public <U> Result<U, E> map(Function<T, U> mapping) { | |
return success(mapping.apply(value)); | |
} | |
@Override | |
public <F> Result<T, F> mapError(Function<E, F> mapping) { | |
return success(value); | |
} | |
@Override | |
public <U> Result<U, E> flatMap(Function<T, Result<U, E>> mapping) { | |
return mapping.apply(value); | |
} | |
@Override | |
public <F> Result<T, F> flatMapError(Function<E, Result<T, F>> mapping) { | |
return success(value); | |
} | |
@Override | |
public T orElse(T ifError) { | |
return value; | |
} | |
@Override | |
public T orElse(Function<E, T> ifError) { | |
return value; | |
} | |
} | |
class Error<T, E> implements Result<T, E> { | |
private final E value; | |
public Error(E value) { | |
this.value = value; | |
} | |
@Override | |
public <U> Result<U, E> map(Function<T, U> mapping) { | |
return error(value); | |
} | |
@Override | |
public <F> Result<T, F> mapError(Function<E, F> mapping) { | |
return error(mapping.apply(value)); | |
} | |
@Override | |
public <U> Result<U, E> flatMap(Function<T, Result<U, E>> mapping) { | |
return error(value); | |
} | |
@Override | |
public <F> Result<T, F> flatMapError(Function<E, Result<T, F>> mapping) { | |
return mapping.apply(value); | |
} | |
@Override | |
public T orElse(T ifError) { | |
return ifError; | |
} | |
@Override | |
public T orElse(Function<E, T> ifError) { | |
return ifError.apply(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment