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
How about this. Some J8 functional switcheroos to avoid ifs on each access. Warning: not thread aware.
import java.util.function.Supplier;
public class Lazy {
private T obj;
private Supplier creator;
private Supplier fieldAccessor = () -> obj;
private Supplier initialGetter = () -> {
obj = creator.get();
creator = null;
initialGetter = null;
getter = fieldAccessor;
return obj;
};
private Supplier getter = initialGetter;
public Lazy(Supplier creator) {
this.creator = creator;
}
public T get() {
return getter.get();
}
}