Skip to content

Instantly share code, notes, and snippets.

@mrange
Created June 12, 2018 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrange/a71f96e33cf35840fed7897b485e1e50 to your computer and use it in GitHub Desktop.
Save mrange/a71f96e33cf35840fed7897b485e1e50 to your computer and use it in GitHub Desktop.
jresult
import java.util.function.Function;
public abstract class Result<T> {
public static <U> Result<U> good(U v) {
return new Good<U>(v);
}
public static <U> Result<U> bad(String message) {
return new Bad<U>(message);
}
public abstract <U> Result<U> then(Function<T, Result<U>> f);
public abstract <U> U test(Function<T, U> ifGood, Function<String, U> ifBad);
static final class Good<T> extends Result<T> {
public final T Value;
public Good(T v) {
Value = v;
}
public <U> Result<U> then(Function<T, Result<U>> f) {
return f.apply(Value);
}
public <U> U test(Function<T, U> ifGood, Function<String, U> ifBad) {
return ifGood.apply(Value);
}
public String toString() {
return "(Good, " + Value.toString() + ")";
}
}
static final class Bad<T> extends Result<T> {
public final String Message;
public Bad(String message) {
Message = message;
}
public <U> Result<U> then(Function<T, Result<U>> f) {
return new Bad<U>(Message);
}
public <U> U test(Function<T, U> ifGood, Function<String, U> ifBad) {
return ifBad.apply(Message);
}
public String toString() {
return "(Bad, " + Message + ")";
}
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class LibraryTest {
@Test public void testGood() {
Result<String> t = Result
.good("Hello")
.then(m -> Result.good(m + " There!"));
Boolean result = t.test(v -> true, msg -> false);
assertTrue(result);
}
@Test public void testBad() {
Result<String> t = Result
.bad("Hello")
.then(m -> Result.good(m + " There!"));
Boolean result = t.test(v -> true, msg -> false);
assertFalse(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment