Created
July 29, 2019 08:17
-
-
Save happy-bracket/8f53035fcfe683fa7edd6bca12115ab8 to your computer and use it in GitHub Desktop.
Java Either, woo hoo
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
class JEither<L, R> { | |
private L left; | |
private R right; | |
private JEither() {} | |
public <C> C fold(Function<L, C> ifLeft, Function<R, C> ifRight) { | |
if (left != null) { | |
return ifLeft.apply(left); | |
} else { | |
return ifRight.apply(right); | |
} | |
} | |
public <C> JEither<L, C> mapRight(Function<R, C> map) { | |
return fold(JEither::Left, map.andThen(JEither::Right)); | |
} | |
public <nR> JEither<L, nR> flatMapRight(Function<R, JEither<L, nR>> fmap) { | |
return fold(JEither::Left, fmap); | |
} | |
public static <L, R> JEither<L, R> Left(L value) { | |
JEither<L, R> e = new JEither<>(); | |
e.left = value; | |
e.right = null; | |
return e; | |
} | |
public static <L, R> JEither<L, R> Right(R value) { | |
JEither<L, R> e = new JEither<>(); | |
e.left = null; | |
e.right = value; | |
return e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment