Search code examples
javavariablesmethodsconstructorfinal

How to initialise a final variable that requires complex computation?


I'm a beginner at Java. I was wondering, what to do in situations where a variable requires complex computation before being initialised, but once initialised, it will not change. I wanted to make the variable final, but instead of initialising it in constructor, I would rather initialise it in a method so this method can be reused later. Is there any way to achieve this?

In addition to all the requirements above, what happen if I want to compute the value of this variable only when I need it (because its computationally expensive to calculate it). What should I do in situations like this?


Solution

  • You can try the memoize supplier from Guava:

    Supplier<T> something = Suppliers.memoize(new Supplier<T>() {
        // heavy computation
        return result.
    });
    
    something.get();
    something.get(); // second call will return the memoized object.