L - The type of the Left value of an Either.R - The type of the Right value of an Either.public abstract class Either<L,R> extends java.lang.Object implements java.lang.Iterable<R>, Value<R>, java.io.Serializable
Either.Left or a
Either.Right.
If the given Either is a Right and projected to a Left, the Left operations have no effect on the Right value.
If the given Either is a Left and projected to a Right, the Right operations have no effect on the Left value.
If a Left is projected to a Left or a Right is projected to a Right, the operations have an effect.
Example: A compute() function, which results either in an Integer value (in the case of success) or in an error message of type String (in the case of failure). By convention the success case is Right and the failure is Left.
Either<String,Integer> value = compute().right().map(i -> i * 2).toEither();
If the result of compute() is Right(1), the value is Right(2).| Modifier and Type | Class and Description |
|---|---|
static class |
Either.Left<L,R>
Deprecated.
will be removed from the public API
|
static class |
Either.LeftProjection<L,R>
Deprecated.
Either is right-biased. Use
swap() instead of projections. |
static class |
Either.Right<L,R>
Deprecated.
will be removed from the public API
|
static class |
Either.RightProjection<L,R>
Deprecated.
Either is right-biased. Use
swap() instead of projections. |
| Modifier and Type | Method and Description |
|---|---|
<X,Y> Either<X,Y> |
bimap(java.util.function.Function<? super L,? extends X> leftMapper,
java.util.function.Function<? super R,? extends Y> rightMapper)
Maps either the left or the right side of this disjunction.
|
Option<Either<L,R>> |
filter(java.util.function.Predicate<? super R> predicate)
Filters this right-biased
Either by testing a predicate. |
Option<Either<L,R>> |
filterNot(java.util.function.Predicate<? super R> predicate)
Filters this right-biased
Either by testing a predicate. |
Either<L,R> |
filterOrElse(java.util.function.Predicate<? super R> predicate,
java.util.function.Function<? super R,? extends L> zero)
Filters this right-biased
Either by testing a predicate. |
<U> Either<L,U> |
flatMap(java.util.function.Function<? super R,? extends Either<L,? extends U>> mapper)
FlatMaps this right-biased Either.
|
<U> U |
fold(java.util.function.Function<? super L,? extends U> leftMapper,
java.util.function.Function<? super R,? extends U> rightMapper)
Folds either the left or the right side of this disjunction.
|
abstract R |
get()
Gets the right value if this is a
Right or throws if this is a Left. |
abstract L |
getLeft()
Returns the left value.
|
R |
getOrElseGet(java.util.function.Function<? super L,? extends R> other)
Gets the Right value or an alternate value, if the projected Either is a Left.
|
<X extends java.lang.Throwable> |
getOrElseThrow(java.util.function.Function<? super L,X> exceptionFunction)
Gets the Right value or throws, if the projected Either is a Left.
|
boolean |
isAsync()
A right-biased
Either's value is computed synchronously. |
boolean |
isEmpty()
Checks, this
Value is empty, i.e. |
boolean |
isLazy()
A right-biased
Either's value is computed eagerly. |
abstract boolean |
isLeft()
Returns whether this Either is a Left.
|
abstract boolean |
isRight()
Returns whether this Either is a Right.
|
boolean |
isSingleValued()
A right-biased
Either is single-valued. |
Iterator<R> |
iterator()
Returns a rich
io.vavr.collection.Iterator. |
Either.LeftProjection<L,R> |
left()
Deprecated.
Either is right-biased. Use
swap() instead of projections. |
static <L,R> Either<L,R> |
left(L left)
Constructs a
Either.Left |
<U> Either<L,U> |
map(java.util.function.Function<? super R,? extends U> mapper)
Maps the value of this Either if it is a Right, performs no operation if this is a Left.
|
<U> Either<U,R> |
mapLeft(java.util.function.Function<? super L,? extends U> leftMapper)
Maps the value of this Either if it is a Left, performs no operation if this is a Right.
|
static <L,R> Either<L,R> |
narrow(Either<? extends L,? extends R> either)
Narrows a widened
Either<? extends L, ? extends R> to Either<L, R>
by performing a type-safe cast. |
Either<L,R> |
orElse(Either<? extends L,? extends R> other) |
Either<L,R> |
orElse(java.util.function.Supplier<? extends Either<? extends L,? extends R>> supplier) |
void |
orElseRun(java.util.function.Consumer<? super L> action)
Runs an action in the case this is a projection on a Left value.
|
Either<L,R> |
peek(java.util.function.Consumer<? super L> leftAction,
java.util.function.Consumer<? super R> rightAction)
Performs the given
leftAction on the left element if this is Left. |
Either<L,R> |
peek(java.util.function.Consumer<? super R> action)
Performs the given
action on the first element if this is an eager implementation. |
Either<L,R> |
peekLeft(java.util.function.Consumer<? super L> action) |
Either<L,R> |
recover(java.util.function.Function<? super L,? extends R> recoveryFunction)
Calls
recoveryFunction if the projected Either is a Left, or returns this if Right. |
Either<L,R> |
recoverWith(java.util.function.Function<? super L,? extends Either<? extends L,? extends R>> recoveryFunction)
Calls recoveryFunction if the projected Either is a Left, performs no operation if this is a Right.
|
Either.RightProjection<L,R> |
right()
Deprecated.
Either is right-biased. Use
swap() instead of projections. |
static <L,R> Either<L,R> |
right(R right)
Constructs a
Either.Right |
static <L,R> Either<Seq<L>,Seq<R>> |
sequence(java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)
Reduces many
Eithers into a single Either by transforming an
Iterable<Either<L, R>> into a Either<Seq<L>, Seq<R>>. |
static <L,R> Either<L,Seq<R>> |
sequenceRight(java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)
Reduces many
Eithers into a single Either by transforming an
Iterable<Either<L, R>> into a Either<L, Seq<R>>. |
Either<R,L> |
swap()
Converts a
Left to a Right vice versa by wrapping the value in a new type. |
Try<R> |
toTry(java.util.function.Function<? super L,? extends java.lang.Throwable> leftMapper)
Transforms this
Either into a Try instance. |
Validation<L,R> |
toValidation()
Returns this as
Validation. |
<U> U |
transform(java.util.function.Function<? super Either<L,R>,? extends U> f)
Transforms this
Either. |
static <L,R,T> Either<Seq<L>,Seq<R>> |
traverse(java.lang.Iterable<? extends T> values,
java.util.function.Function<? super T,? extends Either<? extends L,? extends R>> mapper)
Maps the values of an iterable to a sequence of mapped values into a single
Either by
transforming an Iterable<? extends T> into a Either<Seq<U>>. |
static <L,R,T> Either<L,Seq<R>> |
traverseRight(java.lang.Iterable<? extends T> values,
java.util.function.Function<? super T,? extends Either<? extends L,? extends R>> mapper)
Maps the values of an iterable to a sequence of mapped values into a single
Either by
transforming an Iterable<? extends T> into a Either<Seq<U>>. |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitcollect, collect, contains, corresponds, eq, equals, exists, forAll, forEach, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, hashCode, narrow, out, out, spliterator, stderr, stdout, stringPrefix, toArray, toCharSeq, toCompletableFuture, toEither, toEither, toInvalid, toInvalid, toJavaArray, toJavaArray, toJavaArray, toJavaCollection, toJavaList, toJavaList, toJavaMap, toJavaMap, toJavaMap, toJavaOptional, toJavaParallelStream, toJavaSet, toJavaSet, toJavaStream, toLeft, toLeft, toLinkedMap, toLinkedMap, toLinkedSet, toList, toMap, toMap, toOption, toPriorityQueue, toPriorityQueue, toQueue, toRight, toRight, toSet, toSortedMap, toSortedMap, toSortedMap, toSortedMap, toSortedSet, toSortedSet, toStream, toString, toTree, toTree, toTry, toTry, toValid, toValid, toValidation, toValidation, toVectorpublic static <L,R> Either<L,R> right(R right)
Either.Right
// Creates Either instance initiated with right value 1
Either<?, Integer> either = Either.right(1);
L - Type of left value.R - Type of right value.right - The value.Right instance.public static <L,R> Either<L,R> left(L left)
Either.Left
// Creates Either instance initiated with left value "error message"
Either<String, ?> either = Either.left("error message");
L - Type of left value.R - Type of right value.left - The value.Left instance.public static <L,R> Either<L,R> narrow(Either<? extends L,? extends R> either)
Either<? extends L, ? extends R> to Either<L, R>
by performing a type-safe cast. This is eligible because immutable/read-only
collections are covariant.
// It's ok, Integer inherits from Number
Either<?, Number> answer = Either.right(42);
// RuntimeException is an Exception
Either<Exception, ?> failed = Either.left(new RuntimeException("Vogon poetry recital"));
L - Type of left value.R - Type of right value.either - A Either.either instance as narrowed type Either<L, R>.public abstract L getLeft()
// prints "error"
System.out.println(Either.left("error").getLeft());
// throws NoSuchElementException
System.out.println(Either.right(42).getLeft());
java.util.NoSuchElementException - if this is a Right.public abstract boolean isLeft()
// prints "true"
System.out.println(Either.left("error").isLeft());
// prints "false"
System.out.println(Either.right(42).isLeft());
public abstract boolean isRight()
// prints "true"
System.out.println(Either.right(42).isRight());
// prints "false"
System.out.println(Either.left("error").isRight());
@Deprecated public final Either.LeftProjection<L,R> left()
swap() instead of projections.@Deprecated public final Either.RightProjection<L,R> right()
swap() instead of projections.public final <X,Y> Either<X,Y> bimap(java.util.function.Function<? super L,? extends X> leftMapper, java.util.function.Function<? super R,? extends Y> rightMapper)
Either<?, AtomicInteger> success = Either.right(new AtomicInteger(42));
// prints "Right(42)"
System.out.println(success.bimap(Function1.identity(), AtomicInteger::get));
Either<Exception, ?> failure = Either.left(new Exception("error"));
// prints "Left(error)"
System.out.println(failure.bimap(Exception::getMessage, Function1.identity()));
X - The new left type of the resulting EitherY - The new right type of the resulting EitherleftMapper - maps the left value if this is a LeftrightMapper - maps the right value if this is a Rightpublic final <U> U fold(java.util.function.Function<? super L,? extends U> leftMapper, java.util.function.Function<? super R,? extends U> rightMapper)
Either<Exception, Integer> success = Either.right(3);
// prints "Users updated: 3"
System.out.println(success.fold(Exception::getMessage, count -> "Users updated: " + count));
Either<Exception, Integer> failure = Either.left(new Exception("Failed to update users"));
// prints "Failed to update users"
System.out.println(failure.fold(Exception::getMessage, count -> "Users updated: " + count));
U - type of the folded valueleftMapper - maps the left value if this is a LeftrightMapper - maps the right value if this is a Rightpublic static <L,R> Either<Seq<L>,Seq<R>> sequence(java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)
Eithers into a single Either by transforming an
Iterable<Either<L, R>> into a Either<Seq<L>, Seq<R>>.
If any of the given Eithers is a Either.Left then sequence returns a
Either.Left containing a non-empty Seq of all left values.
If none of the given Eithers is a Either.Left then sequence returns a
Either.Right containing a (possibly empty) Seq of all right values.
// = Right(Seq())
Either.sequence(List.empty())
// = Right(Seq(1, 2))
Either.sequence(List.of(Either.right(1), Either.right(2)))
// = Left(Seq("x"))
Either.sequence(List.of(Either.right(1), Either.left("x")))
L - closure of all left types of the given EithersR - closure of all right types of the given Eitherseithers - An Iterable of EithersEither of a Seq of left or right valuesjava.lang.NullPointerException - if eithers is nullpublic static <L,R,T> Either<Seq<L>,Seq<R>> traverse(java.lang.Iterable<? extends T> values, java.util.function.Function<? super T,? extends Either<? extends L,? extends R>> mapper)
Either by
transforming an Iterable<? extends T> into a Either<Seq<U>>.
Function<Integer, Either<Exception, Double>> validatingMapper =
i -> i < 0 ? Either.left(new Exception("invalid value")) :
Either.right(Math.sqrt(i));
// prints "Right(Vector(2.0, 0.0, 3.0))"
System.out.println(Either.traverse(Seq(4, 0, 9), validatingMapper));
// prints "Left(Vector(java.lang.Exception: invalid value))"
System.out.println(Either.traverse(Seq(4, 0, -12), validatingMapper));
L - The mapped left value type.R - The mapped right value type.T - The type of the given values.values - An Iterable of values.mapper - A mapper of values to EithersEither of a Seq of results.java.lang.NullPointerException - if values or f is null.public static <L,R> Either<L,Seq<R>> sequenceRight(java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)
Eithers into a single Either by transforming an
Iterable<Either<L, R>> into a Either<L, Seq<R>>.
If any of the given Eithers is a Either.Left then sequenceRight returns a
Either.Left containing the first left value (in iteration order).
If none of the given Eithers is a Either.Left then sequenceRight returns a
Either.Right containing a (possibly empty) Seq of all right values.
// = Right(Seq())
Either.sequenceRight(List.empty())
// = Right(Seq(1, 2))
Either.sequenceRight(List.of(Either.right(1), Either.right(2)))
// = Left("x1")
Either.sequenceRight(List.of(Either.right(1), Either.left("x1"), Either.left("x2")))
L - closure of all left types of the given EithersR - closure of all right types of the given Eitherseithers - An Iterable of EithersEither of either a Seq of right values or the first left value, if present.java.lang.NullPointerException - if eithers is nullpublic static <L,R,T> Either<L,Seq<R>> traverseRight(java.lang.Iterable<? extends T> values, java.util.function.Function<? super T,? extends Either<? extends L,? extends R>> mapper)
Either by
transforming an Iterable<? extends T> into a Either<Seq<U>>.
Iterable<String> values = List.of("a", "b", "c");
// prints Right(Vector(a, b, c))
System.out.println(Either.traverseRight(values, Either::right));
// prints Left(a)
System.out.println(Either.traverseRight(values, Either::left));
L - The mapped left value type.R - The mapped right value type.T - The type of the given values.values - An Iterable of values.mapper - A mapper of values to EithersEither of a Seq of results.java.lang.NullPointerException - if values or f is null.public final <U> U transform(java.util.function.Function<? super Either<L,R>,? extends U> f)
Either.
// prints "Anwser is 42"
System.out.println(Either.right(42).<String> transform(e -> "Anwser is " + e.get()));
U - Type of transformation resultf - A transformationUjava.lang.NullPointerException - if f is nullpublic final R getOrElseGet(java.util.function.Function<? super L,? extends R> other)
// prints "42"
System.out.println(Either.right(42).getOrElseGet(l -> -1));
// prints "13"
System.out.println(Either.left("error message").getOrElseGet(String::length));
other - a function which converts a Left value to an alternative Right valueother by applying the Left value.public final void orElseRun(java.util.function.Consumer<? super L> action)
// prints "no value found"
Either.left("no value found").orElseRun(System.out::println);
action - an action which consumes a Left valuepublic final <X extends java.lang.Throwable> R getOrElseThrow(java.util.function.Function<? super L,X> exceptionFunction) throws X extends java.lang.Throwable
Function<String, RuntimeException> exceptionFunction = RuntimeException::new;
// prints "42"
System.out.println(Either.<String, Integer>right(42).getOrElseThrow(exceptionFunction));
// throws RuntimeException("no value found")
Either.left("no value found").getOrElseThrow(exceptionFunction);
X - a throwable typeexceptionFunction - a function which creates an exception based on a Left valueexceptionFunction by applying the Left value.X - if the projected Either is a LeftX extends java.lang.Throwablepublic final Either<R,L> swap()
Left to a Right vice versa by wrapping the value in a new type.
// prints "Right(42)"
System.out.println(Either.left(42).swap());
// prints "Left(message)"
System.out.println(Either.right("message").swap());
Eitherpublic final Either<L,R> recoverWith(java.util.function.Function<? super L,? extends Either<? extends L,? extends R>> recoveryFunction)
getOrElseGet, but where the fallback method also returns an Either.
Either<Integer, String> tryGetString() { return Either.left(1); }
Either<Integer, String> tryGetStringAnotherWay(Integer lvalue) { return Either.right("yo " + lvalue); }
= Right("yo 1")
tryGetString().recover(this::tryGetStringAnotherWay);
recoveryFunction - a function which accepts a Left value and returns an EitherEither<L, R> instancejava.lang.NullPointerException - if the given recoveryFunction is nullpublic final Either<L,R> recover(java.util.function.Function<? super L,? extends R> recoveryFunction)
recoveryFunction if the projected Either is a Left, or returns this if Right. The result
of recoveryFunction will be projected as a Right.
Either<Integer, String> tryGetString() { return Either.left(1); }
String getStringAnotherWay() { return "yo"; }
= Right("yo")
tryGetString().recover(this::getStringAnotherWay);
recoveryFunction - a function which accepts a Left value and returns a Right valueEither<L, R> instancejava.lang.NullPointerException - if the given recoveryFunction is nullpublic final <U> Either<L,U> flatMap(java.util.function.Function<? super R,? extends Either<L,? extends U>> mapper)
// prints "Right(42)"
System.out.println(Either.right(21).flatMap(v -> Either.right(v * 2)));
// prints "Left(error message)"
System.out.println(Either.left("error message").flatMap(Either::right));
U - Component type of the mapped right valuemapper - A mapperEither<L, U> if this is a Left, otherwise the right mapping resultjava.lang.NullPointerException - if mapper is nullpublic final <U> Either<L,U> map(java.util.function.Function<? super R,? extends U> mapper)
// = Right("A")
Either.right("a").map(String::toUpperCase);
// = Left(1)
Either.left(1).map(String::toUpperCase);
public final <U> Either<U,R> mapLeft(java.util.function.Function<? super L,? extends U> leftMapper)
// = Left(2)
Either.left(1).mapLeft(i -> i + 1);
// = Right("a")
Either.right("a").mapLeft(i -> i + 1);
U - Component type of the mapped right valueleftMapper - A mapperMonadjava.lang.NullPointerException - if mapper is nullpublic final Option<Either<L,R>> filter(java.util.function.Predicate<? super R> predicate)
Either by testing a predicate.
predicate - A predicateOption instancejava.lang.NullPointerException - if predicate is nullpublic final Option<Either<L,R>> filterNot(java.util.function.Predicate<? super R> predicate)
Either by testing a predicate.predicate - A predicateEitherjava.lang.NullPointerException - if predicate is nullpublic final Either<L,R> filterOrElse(java.util.function.Predicate<? super R> predicate, java.util.function.Function<? super R,? extends L> zero)
Either by testing a predicate.
If the Either is a Right and the predicate doesn't match, the
Either will be turned into a Left with contents computed by applying
the zero function to the Either value.
// = Left("bad: a")
Either.right("a").filterOrElse(i -> false, val -> "bad: " + val);
// = Right("a")
Either.right("a").filterOrElse(i -> true, val -> "bad: " + val);
predicate - A predicatezero - A function that turns a right value into a left value if the right value does not make it through the filter.Either instancejava.lang.NullPointerException - if predicate is nullpublic abstract R get()
Right or throws if this is a Left.public final boolean isEmpty()
ValueValue is empty, i.e. if the underlying value is absent.public final Either<L,R> orElse(java.util.function.Supplier<? extends Either<? extends L,? extends R>> supplier)
public final boolean isAsync()
Either's value is computed synchronously.public final boolean isLazy()
Either's value is computed eagerly.public final boolean isSingleValued()
Either is single-valued.isSingleValued in interface Value<R>truepublic final Iterator<R> iterator()
Valueio.vavr.collection.Iterator.public final Either<L,R> peek(java.util.function.Consumer<? super L> leftAction, java.util.function.Consumer<? super R> rightAction)
leftAction on the left element if this is Left.
Performs the given rightAction on the right element if this is Right.leftAction - The action that will be performed on the left elementrightAction - The action that will be performed on the right elementpublic final Either<L,R> peek(java.util.function.Consumer<? super R> action)
Valueaction on the first element if this is an eager implementation.
Performs the given action on all elements (the first immediately, successive deferred),
if this is a lazy implementation.public final Validation<L,R> toValidation()
Validation.Validation.valid(get()) if this is right, otherwise Validation.invalid(getLeft()).public final Try<R> toTry(java.util.function.Function<? super L,? extends java.lang.Throwable> leftMapper)
Either into a Try instance.
Map this left value to a Throwable using the leftMapper
or return a Success of this right value.
leftMapper - A function that maps the left value of this Either to a Throwable instanceTry instance that represents the result of the transformationjava.lang.NullPointerException - if leftMapper is null