Is there an object wrapper for primitive values that allows mutating them from a lambda?

347 Views Asked by At

Consider:

boolean somethingHappened = false;
Runnable doHappen = () -> { somethingHappened = true; }

You cannot do that, because somethingHappened is not final. The rationale is that generally, you should not need to change captured variables from the lambda scope. But for example when using Stream.forEach this is not necessary an unusual need.

I could write a wrapper of course:

class Wrap<T> 
{
    public T value;
}

And then I would access somethingHappened.value and change that.

I was just wondering if a wrapper of this kind already exists in the standard Java library. I only know of Optional which is immutable. I could abuse an array final boolean[] mutableBool = { false } but that is horrible.

1

There are 1 best solutions below

5
Thiyagu On BEST ANSWER

Not in Java library. But Apache Commons Lang has Mutable for this. It offers subclasses for each of the primitive wrappers, but each of them is mutable (like MutableInt, MutableBoolean etc)

You can consider if using it would be feasible for you.


UPDATE

AtomicBoolean is another option. It allows you to share it between threads and update the boolean value it holds.


My $0.02 - Whenever I have to update a variable from a lambda, I would step back and re-consider if I really should do it and if using a lambda a right thing for that case. So far (AFAIR), I never had to resort to any approach to overcome the restriction that variables used in a lambda must be effectively final.