Created
June 12, 2018 19:36
-
-
Save mrange/a71f96e33cf35840fed7897b485e1e50 to your computer and use it in GitHub Desktop.
jresult
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; | |
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 + ")"; | |
} | |
} | |
} |
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 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