Class Lazy<T>
java.lang.Object
cloud.opencode.base.functional.monad.Lazy<T>
- Type Parameters:
T- value type - 值类型
- All Implemented Interfaces:
Supplier<T>
Lazy - Lazy evaluation container
Lazy - 惰性求值容器
A container that delays computation until the value is actually needed. The computation is performed at most once, and the result is cached.
延迟计算直到实际需要值的容器。计算最多执行一次,结果会被缓存。
Features | 主要功能:
- Deferred computation - 延迟计算
- Single evaluation (memoization) - 单次求值(记忆化)
- Thread-safe (double-checked locking) - 线程安全(双重检查锁)
- Monadic operations (map, flatMap, filter) - Monad 操作
Usage Examples | 使用示例:
// Deferred computation
Lazy<ExpensiveObject> lazy = Lazy.of(() -> createExpensiveObject());
// Value not computed yet
assertFalse(lazy.isEvaluated());
// Computed on first access
ExpensiveObject obj = lazy.get();
assertTrue(lazy.isEvaluated());
// Cached on subsequent access
ExpensiveObject same = lazy.get(); // No recomputation
// Chained lazy operations
Lazy<String> result = Lazy.of(() -> fetchData())
.map(this::process)
.map(this::format);
// Nothing computed until result.get()
Performance | 性能特性:
- First get(): O(computation time) - 首次 get(): O(计算时间)
- Subsequent get(): O(1) - 后续 get(): O(1)
- Memory: Holds supplier until evaluated - 内存: 保持 supplier 直到求值
Security | 安全性:
- Thread-safe: Yes (DCL) - 线程安全: 是 (双重检查锁)
- Null-safe: Allows null results - 空值安全: 允许 null 结果
- Since:
- JDK 25, opencode-base-functional V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionFilter the value lazily 惰性过滤值<U> Lazy<U> Transform to another Lazy lazily 惰性转换为另一个 Lazyget()Get the value, computing if necessary 获取值,必要时进行计算Get value or compute default if evaluation throws 获取值或计算默认值(如果求值抛出异常)Get value or default if evaluation throws 获取值或默认值(如果求值抛出异常)booleanCheck if the value has been evaluated 检查值是否已被求值<U> Lazy<U> Transform the value lazily 惰性转换值static <T> Lazy<T> Create a Lazy from supplier 从供应商创建 LazytoOption()Convert to Option 转换为 OptiontoString()toTry()Convert to Try 转换为 Trystatic <T> Lazy<T> value(T value) Create an already-evaluated Lazy with value 创建已求值的 Lazy
-
Method Details
-
of
-
value
Create an already-evaluated Lazy with value 创建已求值的 Lazy- Type Parameters:
T- value type - 值类型- Parameters:
value- the value - 值- Returns:
- already-evaluated Lazy
-
get
-
isEvaluated
public boolean isEvaluated()Check if the value has been evaluated 检查值是否已被求值- Returns:
- true if evaluated - 如果已求值返回 true
-
map
Transform the value lazily 惰性转换值The mapper is not applied until the result's get() is called.
映射函数在结果的 get() 被调用前不会执行。
- Type Parameters:
U- result type - 结果类型- Parameters:
mapper- transformation function - 转换函数- Returns:
- lazy transformed value
-
flatMap
-
filter
-
getOrElse
-
getOrElse
-
toTry
-
toOption
-
toString
-