Skip to content

Latest commit

 

History

History
78 lines (57 loc) · 2.43 KB

UseMutablesInLambdas.md

File metadata and controls

78 lines (57 loc) · 2.43 KB

Use to use mutable variables with lamdbas

Contents

The problem

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.

Single Element array solution

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]++;

snippet source | anchor

Mutable solution

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();

snippet source | anchor

Will produce the following:

adding event as Brian
rsvping as Mr. Brian
booking hotel as Steve

snippet source | anchor