Just like java.util.Optional<T>
in Java 8 is (somewhat) equivalent to Scala's Option[T]
type, is there an equivalent to Scala's Either[L, R]
?
8 Answers
There is no Either
type is Java 8, so you need to create one yourself or use some third-party library.
You may build such a feature using the new Optional
type (but read to the end of this answer):
final class Either<L,R>
{
public static <L,R> Either<L,R> left(L value) {
return new Either<>(Optional.of(value), Optional.empty());
}
public static <L,R> Either<L,R> right(R value) {
return new Either<>(Optional.empty(), Optional.of(value));
}
private final Optional<L> left;
private final Optional<R> right;
private Either(Optional<L> l, Optional<R> r) {
left=l;
right=r;
}
public <T> T map(
Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc)
{
return left.<T>map(lFunc).orElseGet(()->right.map(rFunc).get());
}
public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc)
{
return new Either<>(left.map(lFunc),right);
}
public <T> Either<L,T> mapRight(Function<? super R, ? extends T> rFunc)
{
return new Either<>(left, right.map(rFunc));
}
public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc)
{
left.ifPresent(lFunc);
right.ifPresent(rFunc);
}
}
Example use case:
new Random().ints(20, 0, 2).mapToObj(i -> (Either<String,Integer>)(i==0?
Either.left("left value (String)"):
Either.right(42)))
.forEach(either->either.apply(
left ->{ System.out.println("received left value: "+left.substring(11));},
right->{ System.out.println("received right value: 0x"+Integer.toHexString(right));}
));
In retrospective, the Optional
based solution is more like an academic example, but not a recommended approach. One problem is the treatment of null
as “empty” which contradicts the meaning of “either”.
The following code shows an Either
that considers null
a possible value, so it’s strictly “either”, left or right, even if the value is null
:
abstract class Either<L,R>
{
public static <L,R> Either<L,R> left(L value) {
return new Either<L,R>() {
@Override public <T> T map(Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc) {
return lFunc.apply(value);
}
};
}
public static <L,R> Either<L,R> right(R value) {
return new Either<L,R>() {
@Override public <T> T map(Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc) {
return rFunc.apply(value);
}
};
}
private Either() {}
public abstract <T> T map(
Function<? super L, ? extends T> lFunc, Function<? super R, ? extends T> rFunc);
public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc) {
return this.<Either<T,R>>map(t -> left(lFunc.apply(t)), t -> (Either<T,R>)this);
}
public <T> Either<L,T> mapRight(Function<? super R, ? extends T> lFunc) {
return this.<Either<L,T>>map(t -> (Either<L,T>)this, t -> right(lFunc.apply(t)));
}
public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc) {
map(consume(lFunc), consume(rFunc));
}
private <T> Function<T,Void> consume(Consumer<T> c) {
return t -> { c.accept(t); return null; };
}
}
It’s easy to change that to a strict rejection of null
by simply inserting an Objects.requireNonNull(value)
at the beginning of both factory methods. Likewise, adding support for an empty either would be imaginable.
-
12Keep in mind that while this behaves like
Either
, the type is in some sense "too big", since yourleft
andright
fields could in principle both be empty or both be defined. You've hidden the constructors that would make that possible, but the approach still leaves potential for bugs in your implementation. In simple type arithmetic terms, you're trying to geta + b
out of(1 + a) * (1 + b)
. Sure,a + b
occurs in the result of that expression, but so is1
anda * b
. Oct 2, 2014 at 15:52 -
9@Mysterious Dan: forbidding certain kind of state during object construction is the preferred way in Java. Otherwise you would have to invent a new “valid range” type for almost every use case of
int
as using the entire value range ofint
when using anint
variable is the exception, just as an example. After all,Optional
does the same, enforcing the invariants during object construction.– HolgerOct 6, 2014 at 8:17 -
2@Holger:
Either.left(42).map(left -> null, right -> right)
throwsNoSuchElementException
(correct) onthis.right.get()
(incorrect). Also, one can bypass the invariants enforcement and produceEither<empty, empty>
byEither.left(42).mapLeft(left -> null)
. Or when put together, fail again onEither.left(42).mapLeft(left -> null).map(left -> left, right -> right)
.– charlieJun 9, 2016 at 11:52 -
2@charlie: this solution does not consider that
Optional.map
allows the function to returnnull
, turning it to an emptyOptional
. However, besides the opportunity to detect that and throw immediately, I don’t see any alternative solution that is “more correct”. Afaik, there is no reference behavior, as in Scala, you can’t map tonull
…– HolgerJun 9, 2016 at 12:05 -
2@Holger You could have
class Left extends Either
andclass Right extends Either
—that's perfectly Java-style, since it's an use of the Strategy pattern. Oct 27, 2016 at 11:20
At the time of writing, vavr (formerly javaslang) is probably the most popular functional Java 8 library. It is pretty similar to lambda-companion's Either in my other answer.
Either<String,Integer> value = compute().right().map(i -> i * 2).toEither();
There is no Either in the Java Standard Library. However there is an implementation of Either in FunctionalJava, along with many other nice classes.
-
The link to Either seems to have been deleted. Are you sure the project is still being supported ? Jan 10, 2019 at 16:51
-
I have updated the link. The project is still being actively maintained AFAIK. Mar 29, 2019 at 20:02
-
cyclops-react has a 'right' biased either implementation called Xor.
Xor.primary("hello")
.map(s->s+" world")
//Primary["hello world"]
Xor.secondary("hello")
.map(s->s+" world")
//Secondary["hello"]
Xor.secondary("hello")
.swap()
.map(s->s+" world")
//Primary["hello world"]
Xor.accumulateSecondary(ListX.of(Xor.secondary("failed1"),
Xor.secondary("failed2"),
Xor.primary("success")),
Semigroups.stringConcat)
//failed1failed2
There is also a related type Ior which can act as an either or a tuple2.
- disclosure I am the author of cyclops-react.
-
3
Xor
was renamed toEither
in Cyclops X: static.javadoc.io/com.oath.cyclops/cyclops/10.0.0-FINAL/cyclops/…– seanfAug 23, 2018 at 5:56
No, there is none.
Java language developers explicitly state that types like Option<T>
are intended to be used only as temporary values (e.g. in stream operations results), so while they are the same thing as in other languages, they are not supposed to be used as they are used in other languages. So it is not surprising that there is no such thing as Either
because it does not arise naturally (e.g. from stream operations) like Optional
does.
-
9
-
3
-
4For me
Either
does arise naturally. Maybe I'm doing it wrong. What do you do when a method could return two different things? Like,Either<List<String>, SomeOtherClass>
? Oct 20, 2018 at 13:14 -
6I would object too that Either arises naturally, for me in a stream where a map operation could potentially throw an exception, so I map to a stream of Either<Exception, Result> May 15, 2019 at 15:08
-
It arose natually for me, too. So much so, I took @Holder's first implementation with two
Optional
s and polished it to be more useful to me: stackoverflow.com/a/76435293/501113 Jun 8 at 23:26
There is a stand-alone implementation of Either
in a small library, "ambivalence": http://github.com/poetix/ambivalence
You can get it from Maven central:
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>ambivalence</artifactId>
<version>0.2</version>
</dependency>
lambda-companion has an Either
type (and a few other functional types e.g. Try
)
<dependency>
<groupId>no.finn.lambda</groupId>
<artifactId>lambda-companion</artifactId>
<version>0.25</version>
</dependency>
Using it is easy:
final String myValue = Either.right("example").fold(failure -> handleFailure(failure), Function.identity())
-
3
-
NOTE: For an enhanced and fully documented version of the Either
class shown below (including equals
, hashCode
, flatMap
, and other miscellaneous helper functions), please visit this Gist.
I have taken the implementation @Holger provided in his (currently top voted) Answer, and polished it a bit to eliminate all the null
issues I could find.
I refactored it to be more naming convention aligned with the OpenJDK.
I then read through the comments, and made tweaks and adjustments to further improve the quality of the implementation.
I have also added state validation to the constructor, and added a couple of helper methods, isLeft()
, isRight()
, getLeft()
, and getRight()
.
/**
* Implementation of Either<L, R> via a pair of Optionals which explicitly
* reject null values.
* <p>
* Inspired by the (first) solution presented in this StackOverflow Answer:
* <a href="https://stackoverflow.com/a/26164155/501113">...</a>
**/
public static final class Either<L, R> {
public static <L, R> Either<L, R> left(L value) {
return new Either<>(Optional.of(value), Optional.empty());
}
public static <L, R> Either<L, R> right(R value) {
return new Either<>(Optional.empty(), Optional.of(value));
}
private final Optional<L> left;
private final Optional<R> right;
private Either(Optional<L> left, Optional<R> right) {
if (left.isEmpty() == right.isEmpty()) {
throw new IllegalArgumentException(
"left.isEmpty() and right.isEmpty() cannot be equal");
}
this.left = left;
this.right = right;
}
public boolean isLeft() {
return this.left.isPresent();
}
public boolean isRight() {
return this.right.isPresent();
}
public L getLeft() {
return this.left.get();
}
public R getRight() {
return this.right.get();
}
public <T> T map(
Function<? super L, ? extends T> leftFunction,
Function<? super R, ? extends T> rightFunction
) {
return this.left
.<T>map(l -> Objects.requireNonNull(leftFunction.apply(l)))
.orElseGet(() ->
this.right
.map(r -> Objects.requireNonNull(rightFunction.apply(r)))
.orElseThrow(() ->
new IllegalStateException(
"should never get here")));
}
public <T> Either<T, R> mapLeft(
Function<? super L, ? extends T> leftFunction
) {
return new Either<>(
this.left.map(l ->
Objects.requireNonNull(leftFunction.apply(l))),
this.right);
}
public <T> Either<L, T> mapRight(
Function<? super R, ? extends T> rightFunction
) {
return new Either<>(
this.left,
this.right.map(r ->
Objects.requireNonNull(rightFunction.apply(r))));
}
public void forEach(
Consumer<? super L> leftAction,
Consumer<? super R> rightAction
) {
this.left.ifPresent(leftAction);
this.right.ifPresent(rightAction);
}
}
NOTE: For an enhanced and fully documented version of the Either
class shown below (including equals
, hashCode
, flatMap
, and other miscellaneous helper functions), please visit this Gist.
java.lang.Object
... sad.java.utils.Either
might have finally be provided. Nope. So, I just created something as close as I could to what I loved in Scala: stackoverflow.com/a/76435293/501113