Class LazyFinal<T>
java.lang.Object
com.portingdeadmods.portingdeadlibs.utils.LazyFinal<T>
- Type Parameters:
T- the type of the lazy value
- All Implemented Interfaces:
Supplier<T>
A thread-safe write-once lazy container that starts with null value
and can be initialized exactly once.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> LazyFinal<T> create()Factory method to create a new LazyFinal instanceget()Gets the cached value.getOrDefault(T defaultValue) Gets the value if initialized, otherwise returns the default value.Gets the cached value, throwing an exception if not initialized.voidifInitialized(Consumer<T> consumer) Executes the given consumer with the cached value if initialized.voidinitialize(Supplier<T> supplier) Initializes the lazy value using a supplier exactly once.voidinitialize(T value) Initializes the lazy value exactly once.booleanChecks if this lazy container has been initialized.toString()
-
Constructor Details
-
LazyFinal
public LazyFinal()Creates a new LazyFinal instance initialized to null
-
-
Method Details
-
create
Factory method to create a new LazyFinal instance -
initialize
Initializes the lazy value exactly once. Subsequent calls will throw IllegalStateException.- Parameters:
value- the value to initialize with (can be null if you want to explicitly set null)- Throws:
IllegalStateException- if already initialized
-
initialize
Initializes the lazy value using a supplier exactly once. Subsequent calls will throw IllegalStateException.- Parameters:
supplier- the supplier to get the value from- Throws:
IllegalStateException- if already initializedIllegalArgumentException- if supplier returns null
-
ifInitialized
Executes the given consumer with the cached value if initialized. Does nothing if not yet initialized.- Parameters:
consumer- the consumer to execute with the cached value
-
get
Gets the cached value. -
getOrThrow
Gets the cached value, throwing an exception if not initialized.- Returns:
- the cached value
- Throws:
IllegalStateException- if not yet initialized
-
isInitialized
public boolean isInitialized()Checks if this lazy container has been initialized.- Returns:
- true if initialized, false otherwise
-
getOrDefault
Gets the value if initialized, otherwise returns the default value.- Parameters:
defaultValue- the value to return if not initialized- Returns:
- the cached value if initialized, otherwise the default value
-
toString
-