If you are using a value that changes in a lambda, Java will not compile.
For example:
int i = 1;
Function0<Integer> counter = () -> i++;
Will give a compilation error:
Variable used in lambda expression should be final or effectively final
Despite Java wanting the expressions to be final, the truth is that the objects themselves can have mutable state. This means that the workaround is to put the mutable state inside an effectively final object.
Mutable<T>
is a solution to this problem.
The most common solution to this is to use a single element array. While this works, we find it to be ugly.
For example:
final int[] i = {1};
Function0<Integer> counter = () -> i[0]++;
Mutable allows for easy getting/setting/updating.
For example:
Mutable<String> i = new Mutable<>("Brian");
Scheduler scheduler = new Scheduler(() -> i.get());
scheduler.addEvent();
i.update(n -> "Mr. " + n);
scheduler.rsvp();
i.set("Steve");
scheduler.bookHotel();
Will produce the following:
adding event as Brian
rsvping as Mr. Brian
booking hotel as Steve