package ysl.utils;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
public class NullHelper {
/**
* Transforms the provided value if it is not null.
*
* @param value the value to transform
* @param transform the transformation to apply
* @param <T> the type of the provided value
* @param <R> the return type of the transformation
* @return the transformed value or null if the provided value was null
*/
public static <T, R> R nullSafeGet(T value, Function<T, R> transform) {
if (value == null) {
return null;
}
return transform.apply(value);
}
/**
* Transforms the provided value if it is not null or computes a default value.
*
* @param value the original value to transform
* @param transform the transformation to apply if the provided value is not null
* @param supplier the function to compute a default value if the provided one is null
* @param <T> the type of the provided value
* @param <R> the type of the returned value
*/
public static <T, R> R nullSafeGetOr(T value, Function<T, R> transform, Supplier<R> supplier) {
if (value == null) {
return supplier.get();
}
return transform.apply(value);
}
/**
* Returns the first non-null value from the provided arguments.
*
* @throws NullPointerException if there is no non-null value to return
*/
@SafeVarargs
public static <T> T or(T t, Supplier<? extends T>... suppliers) {
if (t != null) {
return t;
}
for (Supplier<? extends T> supplier : suppliers) {
T t1 = supplier.get();
if (t1 != null) {
return t1;
}
}
throw new NullPointerException();
}
}