In the last post I looked at the fundamentals of closures. In this post I will look at some of the things to watch for when using closures.
One of the key takeaway from the last post was the fact that closures captures variables and not values. This has at least one counter intuitive affect on loops.
Consider the following code
On running this the output is
10 10 10 10 10 10 10 10 10 10
To see what’s happening here we can again try and decompose this snippet to what the compiler would do. The code below will not compile because of the use of the non existent keyword ‘ref’ in @AnoymousClass001. This is to illustrate the fact that it is the reference that is being used and not the value. Otherwise int being a value type it would not have been possible to illustrate my point
Hopefully, that explains why we get all 10s instead of numbers in sequence as we really wanted. To get the code to do as we want, we can change our loop block to declare a variable inside the loop block, like so -
This will give us the output as -
0 1 2 3 4 5 6 7 8 9
Hopefully the reason why this works is fairly intuitive by now. The loop variable ‘i’ is shared across all the runs of the loop, while a instance of the variable ‘j’ is created every time the loop block is run