Problem
What will this code print out?
| |
How can we make it print out what we apparently want?
Examples
Example 1
| |
Solution
Method 1 - Fix the closures
The answer of the above function will be:
| |
The original code captures the variable i in the closure, meaning all functions reference the same memory location for i. When the loop ends, the value of i is 3, which is why all functions print 3. To fix this, we need to capture the value of i at each iteration, not the variable reference.
Approach
- Python Solution Fix using Default Arguments:
One way to fix the issue is to use default arguments in the inner function to capture the current value of
i. - Java Solution Using Functional Interface: Since Java doesn’t have closures in the same way, we will create a functional interface and use lambdas.
Fixed Code
| |