One way to do this would be to push the actual instance of the value in question into another class. This will be final, but will not actually be created until the class is loaded, which is deferred until it is needed. Something like the following:
public class MyClass { private static class Loader { public static final INSTANCE = new Foo(); } Foo getInstance() { return Loader.INSTANCE; } }
This will lazily initialize Foo as needed.
If you absolutely need Foo be an instance variable of your top-level class, I can't figure out how to do this. The variable must be filled in the constructor, as you noted.
Actually, I donβt know exactly how Scala works, but I assume that it sets the lazy val variable to some thunk, which is replaced with the actual object on the first evaluation. Scala can, of course, do this by replacing the usual access modifiers in this case, but I donβt think you can transparently do this in Java. You can declare a field, for example. a Future<Foo> , which creates the value on the first call and caches it from this point, but it is not referentially transparent, and by the definition of final I see no way around it.
source share