T - The type of the optional value.public abstract class Option<T> extends java.lang.Object implements java.lang.Iterable<T>, Value<T>, java.io.Serializable
Optional.
Option is a monadic container type which
represents an optional value. Instances of Option are either an instance of Option.Some or the
singleton Option.None.
Most of the API is taken from Optional. A similar type can be found in Haskell and Scala.
| Modifier and Type | Class and Description |
|---|---|
static class |
Option.None<T>
Deprecated.
will be removed from the public API
|
static class |
Option.Some<T>
Deprecated.
will be removed from the public API
|
| Modifier and Type | Method and Description |
|---|---|
<R> Option<R> |
collect(PartialFunction<? super T,? extends R> partialFunction)
Collects value that is in the domain of the given
partialFunction by mapping the value to type R. |
Option<T> |
filter(java.util.function.Predicate<? super T> predicate)
Returns
Some(value) if this is a Some and the value satisfies the given predicate. |
Option<T> |
filterNot(java.util.function.Predicate<? super T> predicate)
Returns
Some(value) if this is a Some and the value not satisfies the given predicate. |
<U> Option<U> |
flatMap(java.util.function.Function<? super T,? extends Option<? extends U>> mapper)
Maps the value to a new
Option if this is a Some, otherwise returns None. |
<U> U |
fold(java.util.function.Supplier<? extends U> ifNone,
java.util.function.Function<? super T,? extends U> f)
Folds either the
None or the Some side of the Option value. |
abstract T |
get()
Gets the value if this is a
Some or throws if this is a None. |
T |
getOrElse(java.util.function.Supplier<? extends T> supplier)
Returns the value if this is a
Some, otherwise supplier.get() is returned. |
T |
getOrElse(T other)
Returns the value if this is a
Some or the other value if this is a None. |
<X extends java.lang.Throwable> |
getOrElseThrow(java.util.function.Supplier<X> exceptionSupplier)
Returns the value if this is a
Some, otherwise throws an exception. |
boolean |
isAsync()
An
Option's value is computed synchronously. |
boolean |
isDefined()
Returns true, if this is
Some, otherwise false, if this is None. |
abstract boolean |
isEmpty()
Returns true, if this is
None, otherwise false, if this is Some. |
boolean |
isLazy()
An
Option's value is computed eagerly. |
boolean |
isSingleValued()
An
Option is single-valued. |
Iterator<T> |
iterator()
Returns a rich
io.vavr.collection.Iterator. |
<U> Option<U> |
map(java.util.function.Function<? super T,? extends U> mapper)
Maps the value and wraps it in a new
Some if this is a Some, otherwise returns a None. |
static <T> Option<T> |
narrow(Option<? extends T> option)
Narrows a widened
Option<? extends T> to Option<T>
by performing a type-safe cast. |
static <T> Option<T> |
none()
Returns the single instance of
None |
static <T> Option<T> |
of(T value)
Creates a new
Option of a given value. |
static <T> Option<T> |
ofOptional(java.util.Optional<? extends T> optional)
Wraps a Java Optional to a new Option
|
Option<T> |
onEmpty(java.lang.Runnable action)
Runs a Java Runnable passed as parameter if this
Option is empty. |
Option<T> |
orElse(Option<? extends T> other)
Returns this
Option if it is nonempty, otherwise return the alternative. |
Option<T> |
orElse(java.util.function.Supplier<? extends Option<? extends T>> supplier)
Returns this
Option if it is nonempty, otherwise return the result of evaluating supplier. |
T |
orNull()
Returns this
Option if this is defined, or null if it is empty. |
Option<T> |
peek(java.util.function.Consumer<? super T> action)
Applies an action to this value, if this option is defined, otherwise does nothing.
|
Option<T> |
peek(java.lang.Runnable noneAction,
java.util.function.Consumer<? super T> someAction)
Performs the given
noneAction if this option is not defined. |
static <T> Option<Seq<T>> |
sequence(java.lang.Iterable<? extends Option<? extends T>> values)
Reduces many
Options into a single Option by transforming an
Iterable<Option<? extends T>> into a Option<Seq<T>>. |
static <T> Option<T> |
some(T value)
Creates a new
Some of a given value. |
<U> U |
transform(java.util.function.Function<? super Option<T>,? extends U> f)
Transforms this
Option. |
static <T,U> Option<Seq<U>> |
traverse(java.lang.Iterable<? extends T> values,
java.util.function.Function<? super T,? extends Option<? extends U>> mapper)
Maps the values of an iterable to a sequence of mapped values into a single
Option by
transforming an Iterable<? extends T> into a Option<Seq<U>>. |
static <T> Option<T> |
when(boolean condition,
java.util.function.Supplier<? extends T> supplier)
Creates
Some of suppliers value if condition is true, or None in other case |
static <T> Option<T> |
when(boolean condition,
T value)
Creates
Some of value if condition is true, or None in other case |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitcollect, collect, contains, corresponds, eq, equals, exists, forAll, forEach, 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 <T> Option<T> of(T value)
Option of a given value.
// = Some(3), an Option which contains the value 3
Option<Integer> option = Option.of(3);
// = None, the empty Option
Option<Integer> none = Option.of(null);
T - type of the valuevalue - A valueSome(value) if value is not null, None otherwisepublic static <T> Option<Seq<T>> sequence(java.lang.Iterable<? extends Option<? extends T>> values)
Options into a single Option by transforming an
Iterable<Option<? extends T>> into a Option<Seq<T>>. If any of
the Options are Option.None, then this returns Option.None.
Seq<Option<Integer>> seq = Vector.of(Option.of(1), Option.of(2), Option.of(3));
// = Some(Seq(1, 2, 3))
Option<Seq<Integer>> option = Option.sequence(seq);
Seq<Option<Integer>> seq = Vector.of(Option.of(1), Option.none());
// = None since some elements in the Iterable are None
Option<Seq<Integer>> option = Option.sequence(seq);
T - type of the Optionsvalues - An Iterable of OptionsOption of a Seq of resultsjava.lang.NullPointerException - if values is nullpublic static <T,U> Option<Seq<U>> traverse(java.lang.Iterable<? extends T> values, java.util.function.Function<? super T,? extends Option<? extends U>> mapper)
Option by
transforming an Iterable<? extends T> into a Option<Seq<U>>.
Function<Integer, Option<String>> mapper = i -> {
if (i <= 0) {
return Option.none();
}
return Option.of("a" = i.toString());
}
// = Some(Seq("a1", "a2", "a3"))
Option<Seq<String>> option = traverse(Vector.of(1, 2, 3), mapper);
// = None
Option<Seq<Integer>> none = traverse(Vector.of(-1, 0, 1), mapper);
T - The type of the given values.U - The mapped value type.values - An Iterable of values.mapper - A mapper of values to OptionsOption of a Seq of results.java.lang.NullPointerException - if values or f is null.public static <T> Option<T> some(T value)
Some of a given value.
The only difference to of(Object) is, when called with argument null.
// = Some(3)
Option.some(3);
// = Some(null)
Option.some(null);
T - type of the valuevalue - A valueSome(value)public static <T> Option<T> none()
None
// = None
Option<String> none = Option.none();
T - component typeNonepublic static <T> Option<T> narrow(Option<? extends T> option)
Option<? extends T> to Option<T>
by performing a type-safe cast. This is eligible because immutable/read-only
collections are covariant.
Option<Integer> option = Option.of(3);
// Narrow to an Option of Number
Option<Number> narrowed = Option.narrow(option);
T - Component type of the Option.option - A Option.option instance as narrowed type Option<T>.public static <T> Option<T> when(boolean condition, java.util.function.Supplier<? extends T> supplier)
Some of suppliers value if condition is true, or None in other case
Supplier<String> supplier = () -> "supplied";
// = Some("supplied")
Option<String> supplied = Option.when(true, supplier);
// = None
Option<String> none = Option.when(false, supplier);
T - type of the optional valuecondition - A boolean valuesupplier - An optional value supplier, may supply nullSome of supplier's value if condition is true, or None in other casejava.lang.NullPointerException - if the given supplier is nullpublic static <T> Option<T> when(boolean condition, T value)
Some of value if condition is true, or None in other case
// = Some(5)
Option<Integer> option = Option.when(true, 5);
// = None
Option<Integer> none = Option.when(false, 5);
T - type of the optional valuecondition - A boolean valuevalue - An optional value, may be nullSome of value if condition is true, or None in other casepublic static <T> Option<T> ofOptional(java.util.Optional<? extends T> optional)
Optional<String> optional = Optional.ofNullable("value");
// Make a Some("value") from an Optional
Option<String> option = Option.ofOptional(optional);
Optional<String> empty = Optional.empty();
// Make a None from an empty Optional
Option<String> none = Option.ofOptional(empty);
T - type of the valueoptional - a given optional to wrap in OptionSome(optional.get()) if value is Java Optional is present, None otherwisepublic final <R> Option<R> collect(PartialFunction<? super T,? extends R> partialFunction)
partialFunction by mapping the value to type R.
partialFunction.isDefinedAt(value)
If the element makes it through that filter, the mapped instance is wrapped in Option
R newValue = partialFunction.apply(value)
R - The new value typepartialFunction - A function that is not necessarily defined on value of this option.Option instance containing value of type Rjava.lang.NullPointerException - if partialFunction is nullpublic abstract boolean isEmpty()
None, otherwise false, if this is Some.
// Prints "false"
System.out.println(Option.of(10).isEmpty());
// Prints "true"
System.out.println(Option.none().isEmpty());
public final Option<T> onEmpty(java.lang.Runnable action)
Option is empty.
Runnable print = () -> System.out.println("Option is empty");
// Prints nothing
Option.of("value").onEmpty(print);
// Prints "Option is empty"
Option.none().onEmpty(print);
action - a given Runnable to be runOptionpublic final boolean isAsync()
Option's value is computed synchronously.
// Prints "false"
System.out.println(Option.of(1).isAsync());
// Prints "false"
System.out.println(Option.none().isAsync());
public final boolean isDefined()
Some, otherwise false, if this is None.
Please note that it is possible to create new Some(null), which is defined.
// Prints "true"
System.out.println(Option.of(10).isDefined());
// Prints "false"
System.out.println(Option.none().isDefined());
// Prints "true
System.out.println(Option.of(null).isDefined());
Option has a defined value, false otherwisepublic final boolean isLazy()
Option's value is computed eagerly.
// Prints "false"
System.out.println(Option.of(3.14).isLazy());
// Prints "false"
System.out.println(Option.none().isLazy());
public final boolean isSingleValued()
Option is single-valued.
// Prints "true"
System.out.println(Option.of("value").isSingleValued());
// Prints "true"
System.out.println(Option.none().isSingleValued());
isSingleValued in interface Value<T>truepublic abstract T get()
Some or throws if this is a None.
// Prints "57"
System.out.println(Option.of(57).get());
// Throws a NoSuchElementException
Option.none().get();
public final T getOrElse(T other)
Some or the other value if this is a None.
Please note, that the other value is eagerly evaluated.
// Prints "Hello"
System.out.println(Option.of("Hello").getOrElse("World"));
// Prints "World"
Option.none().getOrElse("World");
public final Option<T> orElse(Option<? extends T> other)
Option if it is nonempty, otherwise return the alternative.
Option<String> other = Option.of("Other");
// = Some("Hello World")
Option.of("Hello World").orElse(other);
// = Some("Other")
Option.none().orElse(other);
other - An alternative OptionOption if it is nonempty, otherwise return the alternative.public final Option<T> orElse(java.util.function.Supplier<? extends Option<? extends T>> supplier)
Option if it is nonempty, otherwise return the result of evaluating supplier.
Supplier<Option<Integer>> supplier = () -> Option.of(5);
// = Some(2)
Option.of(2).orElse(supplier);
// = Some(5)
Option.none().orElse(supplier);
supplier - An alternative Option supplierOption if it is nonempty, otherwise return the result of evaluating supplier.public final T orNull()
Option if this is defined, or null if it is empty.
// = Some("Hello World")
Option.of("Hello World").orNull();
// = null
Option.none().orNull();
null if it is empty.public final T getOrElse(java.util.function.Supplier<? extends T> supplier)
Some, otherwise supplier.get() is returned.
Please note, that the alternate value is lazily evaluated.
Supplier<Double> supplier = () -> 5.342;
// = 1.2
Option.of(1.2).getOrElse(supplier);
// = 5.342
Option.none().getOrElse(supplier);
public final <X extends java.lang.Throwable> T getOrElseThrow(java.util.function.Supplier<X> exceptionSupplier) throws X extends java.lang.Throwable
Some, otherwise throws an exception.
Supplier<RuntimeException> supplier = () -> new RuntimeException();
// = 12
Option.of(12).getOrElseThrow(supplier);
// throws RuntimeException
Option.none().getOrElseThrow(supplier);
getOrElseThrow in interface Value<T>X - A throwableexceptionSupplier - An exception supplierX - a throwableX extends java.lang.Throwablepublic final Option<T> filter(java.util.function.Predicate<? super T> predicate)
Some(value) if this is a Some and the value satisfies the given predicate.
Otherwise None is returned.
Predicate<Integer> isLessThanTen = i -> i < 10;
// = Some(8)
Option.some(8).filter(isLessThanTen);
// = None
Option.some(12).filter(isLessThanTen);
// = None
Option.<Integer>none().filter(isLessThanTen);
predicate - A predicate which is used to test an optional valueSome(value) or None as specifiedpublic final Option<T> filterNot(java.util.function.Predicate<? super T> predicate)
Some(value) if this is a Some and the value not satisfies the given predicate.
Otherwise None is returned.
Predicate<Integer> isEven = i -> (i & 1) == 0;
// = Some(5)
Option.some(5).filterNot(isEven);
// = None
Option.some(12).filterNot(isEven);
// = None
Option.<Integer>none().filterNot(isEven);
predicate - A predicate which is used to test an optional valueSome(value) or None as specifiedpublic final <U> Option<U> flatMap(java.util.function.Function<? super T,? extends Option<? extends U>> mapper)
Option if this is a Some, otherwise returns None.
Function<Integer, Option<Integer>> mapper = i -> i < 10 ? Option.of(i * 2) : Option.none();
// = Some(14)
Option.of(7).flatMap(mapper);
// = None
Option.of(11).flatMap(mapper);
// = None
Option.<Integer>none().flatMap(mapper);
U - Component type of the resulting Optionmapper - A mapperOptionpublic final <U> Option<U> map(java.util.function.Function<? super T,? extends U> mapper)
Some if this is a Some, otherwise returns a None.
Function<String, String> mapper = s -> s + " World!";
// = Some("Hello World!")
Option.of("Hello").map(mapper);
// = None
Option.<String>none().map(mapper);
public final <U> U fold(java.util.function.Supplier<? extends U> ifNone,
java.util.function.Function<? super T,? extends U> f)
None or the Some side of the Option value.
Supplier<Double> ifNone = () -> 3.14;
Function<String, Double> mapper = s -> Double.valueOf(s) + 0.98;
// = Some(4.98)
Option.of("4").fold(ifNone, mapper);
// = Some(3.14)
Option.<String>none().fold(ifNone, mapper);
U - type of the folded valueifNone - maps the left value if this is a Nonef - maps the value if this is a Somepublic final Option<T> peek(java.lang.Runnable noneAction, java.util.function.Consumer<? super T> someAction)
noneAction if this option is not defined.
Performs the given someAction to this value, if this option is defined.noneAction - The action that will be performed on the left elementsomeAction - The action that will be performed on the right elementpublic final Option<T> peek(java.util.function.Consumer<? super T> action)
Consumer<Integer> print = i -> System.out.println(i);
// Prints 5 and creates Some(8)
Option.of(5).peek(print).map(i -> i + 3);
// Does not print anything
Option.<Integer>none().peek(print);
public final <U> U transform(java.util.function.Function<? super Option<T>,? extends U> f)
Option.
Function<Option<Integer>, String> f = o -> o.getOrElse(3).toString().concat("-transformed"));
// Prints "1-transformed"
System.out.println(Option.of(1).transform(f));
// Prints "3-transformed"
System.out.println(Option.<Integer>none().transform(f));
U - Type of transformation resultf - A transformationUjava.lang.NullPointerException - if f is null