Interface Either<L,R>
- Type Parameters:
L- The type of the Left value.R- The type of the Right value.
- All Superinterfaces:
Iterable<R>,Serializable,Value<R>
- All Known Implementing Classes:
Either.Left,Either.Right
Either.Left or Either.Right.
An Either<L, R> is typically used to model a computation that may result in either
a success (represented by Right) or a failure (represented by Left).
This implementation is right-biased, meaning that most operations such as
map, flatMap, filter, etc., are defined for the Right projection.
This makes Either behave like a monad over its Right type, and enables fluent
chaining of computations in the successful case.
Example
Suppose we have a compute() function that returns an Either<String, Integer>,
where Right represents a successful result and Left holds an error message.
Either<String, Integer> result = compute().map(i -> i * 2);
If compute() returns Right(1), the result will be Right(2).
If compute() returns Left("error"), the result will remain Left("error").
Projection Semantics
- If an
Eitheris aRightand projected toLeft, operations onLeftare no-ops. - If an
Eitheris aLeftand projected toRight, operations onRightare no-ops. - Operations on the matching projection are applied as expected.
- Author:
- Daniel Dietrich, Grzegorz Piwowarek, Adam Kopeć
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic classAn exception wrapper used to propagate values through exception handling mechanisms.static final classTheLeftversion of anEither.static final classDeprecated.Either is right-biased.static final classTheRightversion of anEither.static final classDeprecated.Either is right-biased. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final longThe serial version UID for serialization. -
Method Summary
Modifier and TypeMethodDescriptiondefault <X,Y> Either <X, Y> bimap(@NonNull Function<? super L, ? extends X> leftMapper, @NonNull Function<? super R, ? extends Y> rightMapper) Transforms the value of thisEitherby applying one of the given mapping functions.static <L,R> Either <L, R> cond(boolean test, @NonNull R right, @NonNull L left) Returns anEither<L, R>based on the given test condition.static <L,R> Either <L, R> Returns anEither<L, R>based on the given test condition.booleanClarifies that values have a proper equals() method implemented.Returns anOptiondescribing the right value of this right-biasedEitherif it satisfies the given predicate.filterOrElse(@NonNull Predicate<? super R> predicate, @NonNull Function<? super R, ? extends L> zero) Filters this right-biasedEitherusing the given predicate.Applies a flat-mapping function to the right value of this right-biasedEither.default <U> Ufold(@NonNull Function<? super L, ? extends U> leftMapper, @NonNull Function<? super R, ? extends U> rightMapper) Reduces thisEitherto a single value by applying one of the given functions.get()Returns the right value if this is aRight; otherwise throws.getLeft()Returns the left value of thisEither.default RgetOrElseGet(@NonNull Function<? super L, ? extends R> other) Returns the right value of thisEither, or an alternative value if this is aEither.Left.getOrElseThrow(@NonNull Function<? super L, X> exceptionFunction) Returns the right value of thisEither, or throws an exception if it is aEither.Left.inthashCode()Clarifies that values have a proper hashCode() method implemented.default booleanisAsync()Indicates that a right-biasedEithercomputes its value synchronously.default booleanisEmpty()Checks, thisValueis empty, i.e. if the underlying value is absent.default booleanisLazy()Indicates that a right-biasedEithercomputes its value eagerly.booleanisLeft()Checks whether thisEitheris aEither.Left.booleanisRight()Checks whether thisEitheris aEither.Right.default booleanIndicates that a right-biasedEithercontains exactly one value.iterator()Returns a richio.vavr.collection.Iterator.default Either.LeftProjection<L, R> left()Deprecated.Either is right-biased.static <L,R> Either <L, R> left(L left) Constructs a newEither.Leftinstance containing the given value.Transforms the right value of thisEitherusing the given mapping function.Transforms the left value of thisEitherusing the given mapping function.mapTo(U value) Maps the underlying value to another fixed value.Maps the underlying value to Voidstatic <L,R> Either <L, R> Narrows aEither<? extends L, ? extends R>toEither<L, R>via a type-safe cast.Returns thisEitherif it is aEither.Right, otherwise returns the result of evaluating the givensupplier.default voidExecutes the given action if this projection represents aEither.Leftvalue.Performs the givenactionon the first element if this is an eager implementation.Performs the given action on the left value if this is aEither.Left.default Either.RightProjection<L, R> right()Deprecated.Either is right-biased.static <L,R> Either <L, R> right(R right) Constructs a newEither.Rightinstance containing the given value.sequenceRight(@NonNull Iterable<? extends Either<? extends L, ? extends R>> eithers) swap()toString()Clarifies that values have a proper toString() method implemented.toTry()Converts this to aTry.default Validation<L, R> Returns this asValidation.traverse(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Either<? extends L, ? extends R>> mapper) Transforms anIterableof values into a singleEither<Seq<L>, Seq<R>>by applying a mapping function that returns anEitherfor each value.traverseRight(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Either<? extends L, ? extends R>> mapper) Transforms anIterableof values into a singleEither<Seq<L>, Seq<R>>by applying a mapping function that returns anEitherfor each element.Methods inherited from interface io.vavr.Value
collect, collect, contains, corresponds, eq, exists, forAll, forEach, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, 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, toTree, toTree, toTry, toValid, toValid, toValidation, toValidation, toVector
-
Field Details
-
serialVersionUID
static final long serialVersionUIDThe serial version UID for serialization.- See Also:
-
-
Method Details
-
right
Constructs a newEither.Rightinstance containing the given value.- Type Parameters:
L- the type of the left valueR- the type of the right value- Parameters:
right- the value to store in theRight- Returns:
- a new
Rightinstance
-
left
Constructs a newEither.Leftinstance containing the given value.- Type Parameters:
L- the type of the left valueR- the type of the right value- Parameters:
left- the value to store in theLeft- Returns:
- a new
Leftinstance
-
narrow
Narrows aEither<? extends L, ? extends R>toEither<L, R>via a type-safe cast. This is safe because immutable or read-only collections are covariant.- Type Parameters:
L- the type of the left valueR- the type of the right value- Parameters:
either- theEitherto narrow- Returns:
- the same
eitherinstance cast toEither<L, R>
-
cond
static <L,R> Either<L,R> cond(boolean test, @NonNull Supplier<? extends R> right, @NonNull Supplier<? extends L> left) Returns anEither<L, R>based on the given test condition.- If
testistrue, the result is aEither.Rightcreated fromright. - If
testisfalse, the result is aEither.Leftcreated fromleft.
- Type Parameters:
L- the type of the left valueR- the type of the right value- Parameters:
test- the boolean condition to evaluateright- aSupplier<? extends R>providing the right value iftestis trueleft- aSupplier<? extends L>providing the left value iftestis false- Returns:
- an
Either<L, R>containing the left or right value depending ontest - Throws:
NullPointerException- if any argument is null
- If
-
cond
Returns anEither<L, R>based on the given test condition.- If
testistrue, the result is aEither.Rightcontainingright. - If
testisfalse, the result is aEither.Leftcontainingleft.
- Type Parameters:
L- the type of the left valueR- the type of the right value- Parameters:
test- the boolean condition to evaluateright- theRvalue to return iftestis trueleft- theLvalue to return iftestis false- Returns:
- an
Either<L, R>containing either the left or right value depending ontest - Throws:
NullPointerException- if any argument is null
- If
-
getLeft
L getLeft()Returns the left value of thisEither.- Returns:
- the left value
- Throws:
NoSuchElementException- if thisEitheris aEither.Right
-
isLeft
boolean isLeft()Checks whether thisEitheris aEither.Left.- Returns:
trueif this is aLeft,falseotherwise
-
isRight
boolean isRight()Checks whether thisEitheris aEither.Right.- Returns:
trueif this is aRight,falseotherwise
-
left
Deprecated.Either is right-biased. Useswap()instead of projections.Returns a LeftProjection of this Either.- Returns:
- a new LeftProjection of this
-
right
Deprecated.Either is right-biased. Useswap()instead of projections.Returns a RightProjection of this Either.- Returns:
- a new RightProjection of this
-
bimap
default <X,Y> Either<X,Y> bimap(@NonNull Function<? super L, ? extends X> leftMapper, @NonNull Function<? super R, ? extends Y> rightMapper) Transforms the value of thisEitherby applying one of the given mapping functions.- If this is a
Either.Left,leftMapperis applied to the left value. - If this is a
Either.Right,rightMapperis applied to the right value.
- Type Parameters:
X- the type of the left value in the resultingEitherY- the type of the right value in the resultingEither- Parameters:
leftMapper- function to transform the left value if this is aLeftrightMapper- function to transform the right value if this is aRight- Returns:
- a new
Eitherinstance with the transformed value
- If this is a
-
fold
default <U> U fold(@NonNull Function<? super L, ? extends U> leftMapper, @NonNull Function<? super R, ? extends U> rightMapper) Reduces thisEitherto a single value by applying one of the given functions.- If this is a
Either.Left,leftMapperis applied to the left value. - If this is a
Either.Right,rightMapperis applied to the right value.
- Type Parameters:
U- the type of the resulting value- Parameters:
leftMapper- function to transform the left value if this is aLeftrightMapper- function to transform the right value if this is aRight- Returns:
- a value of type
Uobtained by applying the appropriate function
- If this is a
-
sequence
static <L,R> Either<Seq<L>,Seq<R>> sequence(@NonNull Iterable<? extends Either<? extends L, ? extends R>> eithers) Transforms anIterableofEither<L, R>into a singleEither<Seq<L>, Seq<R>>.If any of the given
Eithers is aEither.Left, the result is aEither.Leftcontaining a non-emptySeqof all left values.If all of the given
Eithers areEither.Right, the result is aEither.Rightcontaining a (possibly empty)Seqof 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")))- Type Parameters:
L- the common type of left valuesR- the common type of right values- Parameters:
eithers- anIterableofEitherinstances- Returns:
- an
Eithercontaining aSeqof left values if anyEitherwas aEither.Left, otherwise aSeqof right values - Throws:
NullPointerException- ifeithersis null
-
traverse
static <L,R, Either<Seq<L>,T> Seq<R>> traverse(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Either<? extends L, ? extends R>> mapper) Transforms anIterableof values into a singleEither<Seq<L>, Seq<R>>by applying a mapping function that returns anEitherfor each value.If the mapper returns any
Either.Left, the resultingEitheris aEither.Leftcontaining aSeqof all left values. Otherwise, the result is aEither.Rightcontaining aSeqof all right values.- Type Parameters:
L- the type of left valuesR- the type of right valuesT- the type of the input values- Parameters:
values- anIterableof values to mapmapper- a function mapping each value to anEither<L, R>- Returns:
- a single
Eithercontaining aSeqof left or right results - Throws:
NullPointerException- ifvaluesormapperis null
-
sequenceRight
static <L,R> Either<L,Seq<R>> sequenceRight(@NonNull Iterable<? extends Either<? extends L, ? extends R>> eithers) Transforms anIterableofEither<L, R>into a singleEither<L, Seq<R>>.If any of the given
Eithers is aEither.Left, the result is aEither.Leftcontaining the first left value encountered in iteration order.If all of the given
Eithers areEither.Right, the result is aEither.Rightcontaining a (possibly empty)Seqof 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")))- Type Parameters:
L- the type of left valuesR- the type of right values- Parameters:
eithers- anIterableofEitherinstances- Returns:
- an
Eithercontaining either the first left value if present, or aSeqof all right values - Throws:
NullPointerException- ifeithersis null
-
traverseRight
static <L,R, Either<L,T> Seq<R>> traverseRight(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Either<? extends L, ? extends R>> mapper) Transforms anIterableof values into a singleEither<Seq<L>, Seq<R>>by applying a mapping function that returns anEitherfor each element.If the mapper returns any
Either.Left, the resultingEitheris aEither.Leftcontaining aSeqof all left values. Otherwise, the result is aEither.Rightcontaining aSeqof all right values.- Type Parameters:
L- the type of left valuesR- the type of right valuesT- the type of input values- Parameters:
values- anIterableof values to mapmapper- a function mapping each value to anEither<L, R>- Returns:
- a single
Eithercontaining aSeqof left or right results - Throws:
NullPointerException- ifvaluesormapperis null
-
getOrElseGet
Returns the right value of thisEither, or an alternative value if this is aEither.Left.- Parameters:
other- a function that converts a left value to an alternative right value- Returns:
- the right value if present, otherwise the alternative value produced by applying
otherto the left value
-
orElseRun
Executes the given action if this projection represents aEither.Leftvalue.- Parameters:
action- a consumer that processes the left value
-
getOrElseThrow
default <X extends Throwable> R getOrElseThrow(@NonNull Function<? super L, X> exceptionFunction) throws XReturns the right value of thisEither, or throws an exception if it is aEither.Left.- Type Parameters:
X- the type of exception to be thrown- Parameters:
exceptionFunction- a function that produces an exception from the left value- Returns:
- the right value if present
- Throws:
X- if thisEitheris aEither.Left, using the exception produced byexceptionFunction
-
swap
- Returns:
- a new
Eitherwith the left and right values swapped
-
flatMap
default <U> Either<L,U> flatMap(@NonNull Function<? super R, ? extends Either<L, ? extends U>> mapper) Applies a flat-mapping function to the right value of this right-biasedEither.If this
Eitheris aEither.Left, it is returned unchanged. Otherwise, themapperfunction is applied to the right value, and its result is returned.- Type Parameters:
U- the type of the right value in the resultingEither- Parameters:
mapper- a function that maps the right value to anotherEither<L, U>- Returns:
- this
Eitherunchanged if it is aEither.Left, or the result of applyingmapperif it is aEither.Right - Throws:
NullPointerException- ifmapperis null
-
map
Transforms the right value of thisEitherusing the given mapping function.If this
Eitheris aEither.Left, no operation is performed and it is returned unchanged.import static io.vavr.API.*; // = Right("A") Right("a").map(String::toUpperCase); // = Left(1) Left(1).map(String::toUpperCase);- Specified by:
mapin interfaceValue<L>- Type Parameters:
U- the type of the right value in the resultingEither- Parameters:
mapper- a function to transform the right value- Returns:
- a new
Eitherwith the right value transformed, or the original left value - Throws:
NullPointerException- ifmapperis null
-
mapLeft
Transforms the left value of thisEitherusing the given mapping function.If this
Eitheris aEither.Right, no operation is performed and it is returned unchanged.import static io.vavr.API.*; // = Left(2) Left(1).mapLeft(i -> i + 1); // = Right("a") Right("a").mapLeft(i -> i + 1);- Type Parameters:
U- the type of the left value in the resultingEither- Parameters:
leftMapper- a function to transform the left value- Returns:
- a new
Eitherwith the left value transformed, or the original right value - Throws:
NullPointerException- ifleftMapperis null
-
filter
Returns anOptiondescribing the right value of this right-biasedEitherif it satisfies the given predicate.If this
Eitheris aEither.Leftor the predicate does not match,Option.none()is returned.- Parameters:
predicate- a predicate to test the right value- Returns:
- an
Optioncontaining the right value if it satisfies the predicate, orOption.none()otherwise - Throws:
NullPointerException- ifpredicateis null
-
filterOrElse
default Either<L,R> filterOrElse(@NonNull Predicate<? super R> predicate, @NonNull Function<? super R, ? extends L> zero) Filters this right-biasedEitherusing the given predicate.If this
Eitheris aEither.Rightand the predicate evaluates tofalse, the result is aEither.Leftobtained by applying thezerofunction to the right value. If the predicate evaluates totrue, theEither.Rightis returned unchanged.import static io.vavr.API.*; // = Left("bad: a") Right("a").filterOrElse(i -> false, val -> "bad: " + val); // = Right("a") Right("a").filterOrElse(i -> true, val -> "bad: " + val);- Parameters:
predicate- a predicate to test the right valuezero- a function that converts a right value to a left value if the predicate fails- Returns:
- an
Eithercontaining the right value if the predicate matches, or a left value otherwise - Throws:
NullPointerException- ifpredicateorzerois null
-
get
R get()Returns the right value if this is aRight; otherwise throws.- Specified by:
getin interfaceValue<L>- Returns:
- the right value
- Throws:
NoSuchElementException- if this is aLeft
-
isEmpty
default boolean isEmpty()Description copied from interface:ValueChecks, thisValueis empty, i.e. if the underlying value is absent. -
orElse
- Parameters:
other- an alternativeEither- Returns:
- this
Eitherif it is aRight, otherwiseother
-
orElse
Returns thisEitherif it is aEither.Right, otherwise returns the result of evaluating the givensupplier.- Parameters:
supplier- a supplier of an alternativeEither- Returns:
- this
Eitherif it is aRight, otherwise the result ofsupplier
-
mapTo
Description copied from interface:ValueMaps the underlying value to another fixed value. -
mapToVoid
Description copied from interface:ValueMaps the underlying value to Void -
isAsync
default boolean isAsync()Indicates that a right-biasedEithercomputes its value synchronously. -
isLazy
default boolean isLazy()Indicates that a right-biasedEithercomputes its value eagerly. -
isSingleValued
default boolean isSingleValued()Indicates that a right-biasedEithercontains exactly one value.- Specified by:
isSingleValuedin interfaceValue<L>- Returns:
true
-
iterator
Description copied from interface:ValueReturns a richio.vavr.collection.Iterator. -
peek
Description copied from interface:ValuePerforms the givenactionon the first element if this is an eager implementation. Performs the givenactionon all elements (the first immediately, successive deferred), if this is a lazy implementation. -
peekLeft
Performs the given action on the left value if this is aEither.Left.If this is a
Either.Right, no action is performed.- Parameters:
action- a consumer that processes the left value- Returns:
- this
Either
-
toValidation
Returns this asValidation.- Returns:
Validation.valid(get())if this is right, otherwiseValidation.invalid(getLeft()).
-
toTry
Description copied from interface:ValueConverts this to aTry.If this value is undefined, i.e. empty, then a new
Failure(NoSuchElementException)is returned, otherwise a newSuccess(value)is returned. -
equals
Description copied from interface:ValueClarifies that values have a proper equals() method implemented. -
hashCode
int hashCode()Description copied from interface:ValueClarifies that values have a proper hashCode() method implemented.See Object.hashCode().
-
toString
String toString()Description copied from interface:ValueClarifies that values have a proper toString() method implemented.See Object.toString().
-