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
You could do something along these lines :
private Supplier heavy = () -> createAndCacheHeavy();
public Heavy getHeavy()
{
return heavy.get();
}
private synchronized Heavy createAndCacheHeavy()
{
class HeavyFactory implements Supplier
{
private final Heavy heavyInstance = new Heavy();
public Heavy get()
{
return heavyInstance;
}
}
if(!HeavyFactory.class.isInstance(heavy))
{
heavy = new HeavyFactory();
}
return heavy.get();
}
I recently saw this as an idea by Venkat Subramaniam. I copied the code from this page.
The basic idea is that the Supplier once called, replaces itself with a simpler factory implementation that returns the initialized instance.
This was in the context of thread safe lazy initialization of a singleton, but you could also apply it to a normal field, obviously.