Interface Either<L,R>
-
- Type Parameters:
L- The type of the Left value.R- The type of the Right value.
- All Superinterfaces:
java.lang.Iterable<R>,java.io.Serializable,Value<R>
- All Known Implementing Classes:
Either.Left,Either.Right
public interface Either<L,R> extends Value<R>, java.io.Serializable
Represents a value of one of two possible types:Either.LeftorEither.Right.An
Either<L, R>is typically used to model a computation that may result in either a success (represented byRight) or a failure (represented byLeft).This implementation is right-biased, meaning that most operations such as
map,flatMap,filter, etc., are defined for theRightprojection. This makesEitherbehave like a monad over itsRighttype, and enables fluent chaining of computations in the successful case.Example
Suppose we have a
compute()function that returns anEither<String, Integer>, whereRightrepresents a successful result andLeftholds an error message.Either<String, Integer> result = compute().map(i -> i * 2);If
compute()returnsRight(1), the result will beRight(2).
Ifcompute()returnsLeft("error"), the result will remainLeft("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.
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static classEither.FailureAn exception wrapper used to propagate values through exception handling mechanisms.static classEither.Left<L,R>TheLeftversion of anEither.static classEither.LeftProjection<L,R>Deprecated.Either is right-biased.static classEither.Right<L,R>TheRightversion of anEither.static classEither.RightProjection<L,R>Deprecated.Either is right-biased.
-
Field Summary
Fields Modifier and Type Field Description static longserialVersionUIDThe serial version UID for serialization.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Deprecated Methods Modifier and Type Method Description default <X,Y>
Either<X,Y>bimap(@NonNull java.util.function.Function<? super L,? extends X> leftMapper, @NonNull java.util.function.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 java.util.function.Supplier<? extends R> right, @NonNull java.util.function.Supplier<? extends L> left)Returns anEither<L, R>based on the given test condition.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.booleanequals(java.lang.Object o)Clarifies that values have a proper equals() method implemented.default Option<Either<L,R>>filter(@NonNull java.util.function.Predicate<? super R> predicate)Returns anOptiondescribing the right value of this right-biasedEitherif it satisfies the given predicate.default Either<L,R>filterOrElse(@NonNull java.util.function.Predicate<? super R> predicate, @NonNull java.util.function.Function<? super R,? extends L> zero)Filters this right-biasedEitherusing the given predicate.default <U> Either<L,U>flatMap(@NonNull java.util.function.Function<? super R,? extends Either<L,? extends U>> mapper)Applies a flat-mapping function to the right value of this right-biasedEither.default <U> Ufold(@NonNull java.util.function.Function<? super L,? extends U> leftMapper, @NonNull java.util.function.Function<? super R,? extends U> rightMapper)Reduces thisEitherto a single value by applying one of the given functions.Rget()Returns the right value if this is aRight; otherwise throws.LgetLeft()Returns the left value of thisEither.default RgetOrElseGet(@NonNull java.util.function.Function<? super L,? extends R> other)Returns the right value of thisEither, or an alternative value if this is aEither.Left.default <X extends java.lang.Throwable>
RgetOrElseThrow(@NonNull java.util.function.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.default booleanisLazy()Indicates that a right-biasedEithercomputes its value eagerly.booleanisLeft()Checks whether thisEitheris aEither.Left.booleanisRight()Checks whether thisEitheris aEither.Right.default booleanisSingleValued()Indicates that a right-biasedEithercontains exactly one value.default @NonNull Iterator<R>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.default <U> Either<L,U>map(@NonNull java.util.function.Function<? super R,? extends U> mapper)Transforms the right value of thisEitherusing the given mapping function.default <U> Either<U,R>mapLeft(@NonNull java.util.function.Function<? super L,? extends U> leftMapper)Transforms the left value of thisEitherusing the given mapping function.default <U> Either<L,U>mapTo(U value)Maps the underlying value to another fixed value.default Either<L,java.lang.Void>mapToVoid()Maps the underlying value to Voidstatic <L,R>
Either<L,R>narrow(Either<? extends L,? extends R> either)Narrows aEither<? extends L, ? extends R>toEither<L, R>via a type-safe cast.default Either<L,R>orElse(@NonNull Either<? extends L,? extends R> other)default Either<L,R>orElse(@NonNull java.util.function.Supplier<? extends Either<? extends L,? extends R>> supplier)Returns thisEitherif it is aEither.Right, otherwise returns the result of evaluating the givensupplier.default voidorElseRun(@NonNull java.util.function.Consumer<? super L> action)Executes the given action if this projection represents aEither.Leftvalue.default Either<L,R>peek(@NonNull java.util.function.Consumer<? super R> action)Performs the givenactionon the first element if this is an eager implementation.default Either<L,R>peekLeft(@NonNull java.util.function.Consumer<? super L> action)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.static <L,R>
Either<Seq<L>,Seq<R>>sequence(@NonNull java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)Transforms anIterableofEither<L, R>into a singleEither<Seq<L>, Seq<R>>.static <L,R>
Either<L,Seq<R>>sequenceRight(@NonNull java.lang.Iterable<? extends Either<? extends L,? extends R>> eithers)Transforms anIterableofEither<L, R>into a singleEither<L, Seq<R>>.default Either<R,L>swap()java.lang.StringtoString()Clarifies that values have a proper toString() method implemented.default Try<R>toTry()Converts this to aTry.default Validation<L,R>toValidation()Returns this asValidation.static <L,R,T>
Either<Seq<L>,Seq<R>>traverse(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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.static <L,R,T>
Either<L,Seq<R>>traverseRight(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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 Detail
-
serialVersionUID
static final long serialVersionUID
The serial version UID for serialization.- See Also:
- Constant Field Values
-
-
Method Detail
-
right
static <L,R> Either<L,R> right(R 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
static <L,R> Either<L,R> left(L 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
static <L,R> Either<L,R> narrow(Either<? extends L,? extends R> either)
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 java.util.function.Supplier<? extends R> right, @NonNull java.util.function.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:
java.lang.NullPointerException- if any argument is null
- If
-
cond
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.- 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:
java.lang.NullPointerException- if any argument is null
- If
-
getLeft
L getLeft()
Returns the left value of thisEither.- Returns:
- the left value
- Throws:
java.util.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 default Either.LeftProjection<L,R> left()
Deprecated.Either is right-biased. Useswap()instead of projections.Returns a LeftProjection of this Either.- Returns:
- a new LeftProjection of this
-
right
@Deprecated default Either.RightProjection<L,R> 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 java.util.function.Function<? super L,? extends X> leftMapper, @NonNull java.util.function.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 java.util.function.Function<? super L,? extends U> leftMapper, @NonNull java.util.function.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 java.lang.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:
java.lang.NullPointerException- ifeithersis null
-
traverse
static <L,R,T> Either<Seq<L>,Seq<R>> traverse(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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:
java.lang.NullPointerException- ifvaluesormapperis null
-
sequenceRight
static <L,R> Either<L,Seq<R>> sequenceRight(@NonNull java.lang.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:
java.lang.NullPointerException- ifeithersis null
-
traverseRight
static <L,R,T> Either<L,Seq<R>> traverseRight(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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:
java.lang.NullPointerException- ifvaluesormapperis null
-
getOrElseGet
default R getOrElseGet(@NonNull java.util.function.Function<? super L,? extends R> other)
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
default void orElseRun(@NonNull java.util.function.Consumer<? super L> action)
Executes the given action if this projection represents aEither.Leftvalue.- Parameters:
action- a consumer that processes the left value
-
getOrElseThrow
default <X extends java.lang.Throwable> R getOrElseThrow(@NonNull java.util.function.Function<? super L,X> exceptionFunction) throws X extends java.lang.Throwable
Returns 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 byexceptionFunctionX extends java.lang.Throwable
-
flatMap
default <U> Either<L,U> flatMap(@NonNull java.util.function.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:
java.lang.NullPointerException- ifmapperis null
-
map
default <U> Either<L,U> map(@NonNull java.util.function.Function<? super R,? extends U> mapper)
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:
java.lang.NullPointerException- ifmapperis null
-
mapLeft
default <U> Either<U,R> mapLeft(@NonNull java.util.function.Function<? super L,? extends U> leftMapper)
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:
java.lang.NullPointerException- ifleftMapperis null
-
filter
default Option<Either<L,R>> filter(@NonNull java.util.function.Predicate<? super R> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
filterOrElse
default Either<L,R> filterOrElse(@NonNull java.util.function.Predicate<? super R> predicate, @NonNull java.util.function.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:
java.lang.NullPointerException- ifpredicateorzerois null
-
get
R get()
Returns the right value if this is aRight; otherwise throws.
-
isEmpty
default boolean isEmpty()
Description copied from interface:ValueChecks, thisValueis empty, i.e. if the underlying value is absent.
-
orElse
default Either<L,R> orElse(@NonNull Either<? extends L,? extends R> other)
- Parameters:
other- an alternativeEither- Returns:
- this
Eitherif it is aRight, otherwiseother
-
orElse
default Either<L,R> orElse(@NonNull java.util.function.Supplier<? extends Either<? extends L,? extends R>> supplier)
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
default <U> Either<L,U> mapTo(U value)
Description copied from interface:ValueMaps the underlying value to another fixed value.
-
mapToVoid
default Either<L,java.lang.Void> 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
default @NonNull Iterator<R> iterator()
Description copied from interface:ValueReturns a richio.vavr.collection.Iterator.
-
peek
default Either<L,R> peek(@NonNull java.util.function.Consumer<? super R> action)
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
default Either<L,R> peekLeft(@NonNull java.util.function.Consumer<? super L> action)
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
default Validation<L,R> toValidation()
Returns this asValidation.- Returns:
Validation.valid(get())if this is right, otherwiseValidation.invalid(getLeft()).
-
toTry
default Try<R> 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
boolean equals(java.lang.Object o)
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
java.lang.String toString()
Description copied from interface:ValueClarifies that values have a proper toString() method implemented.See Object.toString().
-
-