Package io.vavr

Class 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 standard Supplier, Lazy is 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 flatMap or orElse.

    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.123
     

    Creating a truly lazy value for an interface type:

    
     final CharSequence chars = Lazy.val(() -> "Yay!", CharSequence.class);
     
    See Also:
    Serialized Form
    • Field Detail

      • 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 a Lazy<? extends T> to Lazy<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 a Lazy instance that obtains its value from the given Supplier. 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 Lazy instance
      • sequence

        public static <T> Lazy<Seq<T>> sequence​(@NonNull java.lang.Iterable<? extends Lazy<? extends T>> values)
        Combines multiple Lazy instances into a single Lazy containing a sequence of their evaluated values.

        Transforms an Iterable<Lazy<? extends T>> into a Lazy<Seq<T>>, evaluating each value lazily when the resulting Lazy is accessed.

        Type Parameters:
        T - the type of the lazy values
        Parameters:
        values - an Iterable of lazy values
        Returns:
        a Lazy containing a sequence of the evaluated values
        Throws:
        java.lang.NullPointerException - if values is 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 type T, implemented using a Proxy that delegates to a Lazy instance.
        Type Parameters:
        T - the type of the lazy value
        Parameters:
        supplier - the supplier providing the value when needed
        type - the interface class that the proxy should implement
        Returns:
        a new proxy instance of type T that 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 Some containing the value. Otherwise, it returns None.

        Parameters:
        predicate - the predicate to test the value
        Returns:
        Some(value) if the predicate is satisfied, None otherwise
        Throws:
        java.lang.NullPointerException - if predicate is null
      • get

        public T get()
        Evaluates this lazy value on the first call and caches the result. Subsequent calls return the cached value without recomputation.
        Specified by:
        get in interface java.util.function.Supplier<T>
        Specified by:
        get in interface Value<T>
        Returns:
        the evaluated value
      • computeValue

        private T computeValue()
      • isAsync

        public boolean isAsync()
        Indicates that this Lazy value is computed synchronously.
        Specified by:
        isAsync in interface Value<T>
        Returns:
        false
      • isEmpty

        public boolean isEmpty()
        Description copied from interface: Value
        Checks, this Value is empty, i.e. if the underlying value is absent.
        Specified by:
        isEmpty in interface Value<T>
        Returns:
        false, if no underlying value is present, true otherwise.
      • 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:
        true if the value has been evaluated, false otherwise
        Throws:
        java.lang.UnsupportedOperationException - if this lazy value is undefined
      • isLazy

        public boolean isLazy()
        Indicates that this Lazy value is computed lazily.
        Specified by:
        isLazy in interface Value<T>
        Returns:
        true
      • isSingleValued

        public boolean isSingleValued()
        Description copied from interface: Value
        States whether this is a single-valued type.
        Specified by:
        isSingleValued in interface Value<T>
        Returns:
        true if this is single-valued, false otherwise.
      • iterator

        public @NonNull Iterator<T> iterator()
        Description copied from interface: Value
        Returns a rich io.vavr.collection.Iterator.
        Specified by:
        iterator in interface java.lang.Iterable<T>
        Specified by:
        iterator in interface Value<T>
        Returns:
        A new Iterator
      • map

        public <U> Lazy<U> map​(@NonNull java.util.function.Function<? super T,​? extends U> mapper)
        Description copied from interface: Value
        Maps the underlying value to a different component type.
        Specified by:
        map in interface Value<T>
        Type Parameters:
        U - The new component type
        Parameters:
        mapper - A mapper
        Returns:
        A new value
      • mapTo

        public <U> Lazy<U> mapTo​(U value)
        Description copied from interface: Value
        Maps the underlying value to another fixed value.
        Specified by:
        mapTo in interface Value<T>
        Type Parameters:
        U - The new component type
        Parameters:
        value - value to replace the contents with
        Returns:
        A new value
      • mapToVoid

        public Lazy<java.lang.Void> mapToVoid()
        Description copied from interface: Value
        Maps the underlying value to Void
        Specified by:
        mapToVoid in interface Value<T>
        Returns:
        A new value of type Void
      • peek

        public Lazy<T> peek​(@NonNull java.util.function.Consumer<? super T> action)
        Description copied from interface: Value
        Performs the given action 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.
        Specified by:
        peek in interface Value<T>
        Parameters:
        action - The action that will be performed on the element(s).
        Returns:
        this instance
      • 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 this Lazy, producing a new Lazy instance 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 Lazy instance containing the transformed value
        Throws:
        java.lang.NullPointerException - if f is null
      • stringPrefix

        public java.lang.String stringPrefix()
        Description copied from interface: Value
        Returns the name of this Value type, which is used by toString().
        Specified by:
        stringPrefix in interface Value<T>
        Returns:
        This type name.
      • equals

        public boolean equals​(java.lang.Object o)
        Description copied from interface: Value
        Clarifies that values have a proper equals() method implemented.

        See Object.equals(Object).

        Specified by:
        equals in interface Value<T>
        Overrides:
        equals in class java.lang.Object
        Parameters:
        o - An object
        Returns:
        true, if this equals o, false otherwise
      • hashCode

        public int hashCode()
        Description copied from interface: Value
        Clarifies that values have a proper hashCode() method implemented.

        See Object.hashCode().

        Specified by:
        hashCode in interface Value<T>
        Overrides:
        hashCode in class java.lang.Object
        Returns:
        The hashcode of this object
      • toString

        public java.lang.String toString()
        Description copied from interface: Value
        Clarifies that values have a proper toString() method implemented.

        See Object.toString().

        Specified by:
        toString in interface Value<T>
        Overrides:
        toString in class java.lang.Object
        Returns:
        A String representation of this object
      • 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