Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
Thor Avatar asked Apr 30 '26 18:04

Thor


2 Answers

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.
like image 177
xiaofeng.li Avatar answered May 02 '26 08:05

xiaofeng.li


Unfortunately, you can't make a variable final in just any given moment. If a variable is final it can (and must) be initialized in the constructor.

You could also do this (credit to npinti for following code):

private boolean isMutable;
private String someString;

public void setMutable(boolean value)
{
    this.isMutable = value;
}

public void setSomeString(String value)
{
    if (this.isMutable)
    {
        this.someString = value;
    }
}
like image 41
Michael Avatar answered May 02 '26 08:05

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!