[main] Allow null in lazy supplier

This commit is contained in:
Johannes Frohnmeyer 2022-06-21 18:37:33 +02:00
parent b8d496f716
commit e50ddd7d82
Signed by: Johannes
GPG Key ID: E76429612C2929F4
1 changed files with 6 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package io.gitlab.jfronny.commons;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.function.Function;
@ -13,16 +14,18 @@ import java.util.function.Supplier;
public class LazySupplier<T> implements Supplier<T> {
private final Supplier<T> supplier;
private T cache = null;
private boolean initialized;
/**
* Create a lazy supplier from a pre-initialized value.
* The backing supplier will be empty and never called.
* @param value The value to initialize the cache with
*/
public LazySupplier(@NotNull T value) {
public LazySupplier(@Nullable T value) {
this.supplier = () -> {
throw new RuntimeException("Supplier should have never been called");
};
initialized = true;
cache = value;
}
@ -33,10 +36,11 @@ public class LazySupplier<T> implements Supplier<T> {
*/
public LazySupplier(@NotNull Supplier<T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
initialized = false;
}
@Override @Contract(pure = true) @NotNull public T get() {
if (cache == null) cache = supplier.get();
if (!initialized) cache = supplier.get();
return cache;
}