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?
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With