I would like to implement lazy field initialization (or deferred initialization) without an if statement and taking advantage of lambdas. So, I would like to have the same b
Here's a way that also works if you want to pass arguments (which you dont have when initializing the functional interface) to your expensiveInit method.
public final class Cache {
private Function, T> supplier;
private Cache(){
supplier = s -> {
T value = s.get();
supplier = n -> value;
return value;
};
}
public static Supplier of(Supplier extends T> creater){
Cache c = new Cache<>();
return () -> c.supplier.apply(creater);
}
public static Function of(Function super U, ? extends T> creater){
Cache c = new Cache<>();
return u -> c.supplier.apply(() -> creater.apply(u));
}
public static BiFunction of(BiFunction super U, ? super V, ? extends T> creater){
Cache c = new Cache<>();
return (u, v) -> c.supplier.apply(() -> creater.apply(u, v));
}
}
Usage is the same as Stuart Marks' answer:
private final Function lazyBar = Cache.of(this::expensiveBarForFoo);