Package io.vavr
Class Lazy<T>
- java.lang.Object
-
- io.vavr.Lazy<T>
-
- Type Parameters:
T- the type of the lazily evaluated value
- All Implemented Interfaces:
Value<T>,java.io.Serializable,java.lang.Iterable<T>,java.util.function.Supplier<T>
public final class Lazy<T> extends java.lang.Object implements Value<T>, java.util.function.Supplier<T>, java.io.Serializable
Represents a lazily evaluated value. Unlike a standardSupplier,Lazyis memoizing: the computation is performed at most once, ensuring referential transparency.This type behaves more like a Functor than a Monad: it represents a value rather than capturing a specific state. Therefore, it does not provide operations like
flatMapororElse.Example usage:
final Lazy<Double> l = Lazy.of(Math::random); l.isEvaluated(); // false double value = l.get(); // evaluates and returns a random number, e.g., 0.123 l.isEvaluated(); // true double memoizedValue = l.get(); // returns the same value as before, e.g., 0.123Creating a truly lazy value for an interface type:
final CharSequence chars = Lazy.val(() -> "Yay!", CharSequence.class);- See Also:
- Serialized Form
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private TcomputeValue()booleanequals(java.lang.Object o)Clarifies that values have a proper equals() method implemented.Option<T>filter(@NonNull java.util.function.Predicate<? super T> predicate)Filters this lazy value by applying the given predicate to the evaluated value.Tget()Evaluates this lazy value on the first call and caches the result.inthashCode()Clarifies that values have a proper hashCode() method implemented.booleanisAsync()Indicates that thisLazyvalue is computed synchronously.booleanisEmpty()Checks, thisValueis empty, i.e.booleanisEvaluated()Checks whether this lazy value has been evaluated.booleanisLazy()Indicates that thisLazyvalue is computed lazily.booleanisSingleValued()States whether this is a single-valued type.@NonNull Iterator<T>iterator()Returns a richio.vavr.collection.Iterator.<U> Lazy<U>map(@NonNull java.util.function.Function<? super T,? extends U> mapper)Maps the underlying value to a different component type.<U> Lazy<U>mapTo(U value)Maps the underlying value to another fixed value.Lazy<java.lang.Void>mapToVoid()Maps the underlying value to Voidstatic <T> Lazy<T>narrow(Lazy<? extends T> lazy)Narrows aLazy<? extends T>toLazy<T>via a type-safe cast.static <T> Lazy<T>of(@NonNull java.util.function.Supplier<? extends T> supplier)Creates aLazyinstance that obtains its value from the givenSupplier.Lazy<T>peek(@NonNull java.util.function.Consumer<? super T> action)Performs the givenactionon the first element if this is an eager implementation.static <T> Lazy<Seq<T>>sequence(@NonNull java.lang.Iterable<? extends Lazy<? extends T>> values)Combines multipleLazyinstances into a singleLazycontaining a sequence of their evaluated values.java.lang.StringstringPrefix()Returns the name of this Value type, which is used by toString().java.lang.StringtoString()Clarifies that values have a proper toString() method implemented.<U> Utransform(@NonNull java.util.function.Function<? super Lazy<T>,? extends U> f)Applies a transformation function to the value contained in thisLazy, producing a newLazyinstance of the transformed value.static <T> Tval(@NonNull java.util.function.Supplier<? extends T> supplier, @NonNull java.lang.Class<T> type)Creates a true lazy value of typeT, implemented using a Proxy that delegates to aLazyinstance.private voidwriteObject(java.io.ObjectOutputStream s)Forces the lazy value to be evaluated before it is serialized.-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
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, 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, toTry, toValid, toValid, toValidation, toValidation, toVector
-
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
lock
private final java.util.concurrent.locks.ReentrantLock lock
-
supplier
private transient volatile java.util.function.Supplier<? extends T> supplier
-
value
private T value
-
-
Constructor Detail
-
Lazy
private Lazy(java.util.function.Supplier<? extends T> supplier)
-
-
Method Detail
-
narrow
public static <T> Lazy<T> narrow(Lazy<? extends T> lazy)
Narrows aLazy<? extends T>toLazy<T>via a type-safe cast. Safe here because the lazy value is immutable and no elements can be added that would violate the type (covariance)- Type Parameters:
T- the target element type- Parameters:
lazy- the lazy value to narrow- Returns:
- the same lazy value viewed as
Lazy<T>
-
of
public static <T> Lazy<T> of(@NonNull java.util.function.Supplier<? extends T> supplier)
Creates aLazyinstance that obtains its value from the givenSupplier. The supplier is invoked at most once, and the result is cached for subsequent calls.- Type Parameters:
T- the type of the lazy value- Parameters:
supplier- the supplier providing the value- Returns:
- a new
Lazyinstance
-
sequence
public static <T> Lazy<Seq<T>> sequence(@NonNull java.lang.Iterable<? extends Lazy<? extends T>> values)
Combines multipleLazyinstances into a singleLazycontaining a sequence of their evaluated values.Transforms an
Iterable<Lazy<? extends T>>into aLazy<Seq<T>>, evaluating each value lazily when the resultingLazyis accessed.- Type Parameters:
T- the type of the lazy values- Parameters:
values- anIterableof lazy values- Returns:
- a
Lazycontaining a sequence of the evaluated values - Throws:
java.lang.NullPointerException- ifvaluesis null
-
val
@GwtIncompatible("reflection is not supported") public static <T> T val(@NonNull java.util.function.Supplier<? extends T> supplier, @NonNull java.lang.Class<T> type)
Creates a true lazy value of typeT, implemented using a Proxy that delegates to aLazyinstance.- Type Parameters:
T- the type of the lazy value- Parameters:
supplier- the supplier providing the value when neededtype- the interface class that the proxy should implement- Returns:
- a new proxy instance of type
Tthat evaluates lazily
-
filter
public Option<T> filter(@NonNull java.util.function.Predicate<? super T> predicate)
Filters this lazy value by applying the given predicate to the evaluated value.If the predicate matches the evaluated value, it returns
Somecontaining the value. Otherwise, it returnsNone.- Parameters:
predicate- the predicate to test the value- Returns:
Some(value)if the predicate is satisfied,Noneotherwise- Throws:
java.lang.NullPointerException- ifpredicateisnull
-
get
public T get()
Evaluates this lazy value on the first call and caches the result. Subsequent calls return the cached value without recomputation.
-
computeValue
private T computeValue()
-
isAsync
public boolean isAsync()
Indicates that thisLazyvalue is computed synchronously.
-
isEmpty
public boolean isEmpty()
Description copied from interface:ValueChecks, thisValueis empty, i.e. if the underlying value is absent.
-
isEvaluated
public boolean isEvaluated()
Checks whether this lazy value has been evaluated.Note: The value is evaluated internally (at most once) when
get()is called.- Returns:
trueif the value has been evaluated,falseotherwise- Throws:
java.lang.UnsupportedOperationException- if this lazy value is undefined
-
isLazy
public boolean isLazy()
Indicates that thisLazyvalue is computed lazily.
-
isSingleValued
public boolean isSingleValued()
Description copied from interface:ValueStates whether this is a single-valued type.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
trueif this is single-valued,falseotherwise.
-
iterator
public @NonNull Iterator<T> iterator()
Description copied from interface:ValueReturns a richio.vavr.collection.Iterator.
-
map
public <U> Lazy<U> map(@NonNull java.util.function.Function<? super T,? extends U> mapper)
Description copied from interface:ValueMaps the underlying value to a different component type.
-
mapTo
public <U> Lazy<U> mapTo(U value)
Description copied from interface:ValueMaps the underlying value to another fixed value.
-
mapToVoid
public Lazy<java.lang.Void> mapToVoid()
Description copied from interface:ValueMaps the underlying value to Void
-
peek
public Lazy<T> peek(@NonNull java.util.function.Consumer<? super T> 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.
-
transform
public <U> U transform(@NonNull java.util.function.Function<? super Lazy<T>,? extends U> f)
Applies a transformation function to the value contained in thisLazy, producing a newLazyinstance of the transformed value.- Type Parameters:
U- the type of the result of the transformation- Parameters:
f- the function to transform the value- Returns:
- a new
Lazyinstance containing the transformed value - Throws:
java.lang.NullPointerException- iffis null
-
stringPrefix
public java.lang.String stringPrefix()
Description copied from interface:ValueReturns the name of this Value type, which is used by toString().- Specified by:
stringPrefixin interfaceValue<T>- Returns:
- This type name.
-
equals
public boolean equals(java.lang.Object o)
Description copied from interface:ValueClarifies that values have a proper equals() method implemented.
-
hashCode
public int hashCode()
Description copied from interface:ValueClarifies that values have a proper hashCode() method implemented.See Object.hashCode().
-
toString
public java.lang.String toString()
Description copied from interface:ValueClarifies that values have a proper toString() method implemented.See Object.toString().
-
writeObject
@GwtIncompatible("The Java serialization protocol is explicitly not supported") private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException
Forces the lazy value to be evaluated before it is serialized.- Parameters:
s- the object output stream to write to- Throws:
java.io.IOException- if an I/O error occurs during serialization
-
-