tags:

views:

183

answers:

1

I am new to JavaFX. I am not able to understand why the code below doesn't work.

import javafx.util.Sequences;

def nums = [1..10];
var curr = 0;

var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number";

for (curr in [0..(sizeof nums -1)])
{
    println("{evenOrOdd}");
}

I am getting

1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number
1 is an odd number

If I change the code to

import javafx.util.Sequences;

def nums = [1..10];
var curr = 0;

var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number";

for (i in [0..(sizeof nums -1)])
{
    curr = i;
    println("{evenOrOdd}");
}

I get the correct output:

1 is an odd number
2 is an even number
3 is an odd number
4 is an even number
5 is an odd number
6 is an even number
7 is an odd number
8 is an even number
9 is an odd number
10 is an even number

Clearly, the counter increment in the loop is not treated as a value change and the bound expression is not re evaluated.

Can anyone please explain the concept behind this behavior?

+4  A: 

The for expression implicitly defines its iteration variable (that's why you didn't need to declare i in your second example). Even if there is already a variable with the same name, for will still create a new one for its scope. Your bind expression is bound to the curr variable outside of your for loop, not to the one inside your for loop. And the one outside of your loop doesn't change, so the bound expression will not change.

Example to demonstrate this behaviour of for:

var curr = 0;
var ousideCurrRef = bind curr;
println("Before 'for' loop: curr={curr}");
for (curr in [0..3])
{
    println("In 'for' loop: curr={curr} ousideCurrRef={ousideCurrRef}");
}
println("After 'for' loop: curr={curr}");

This will print:

Before 'for' loop: curr=0
In 'for' loop: curr=0 ousideCurrRef=0
In 'for' loop: curr=1 ousideCurrRef=0
In 'for' loop: curr=2 ousideCurrRef=0
In 'for' loop: curr=3 ousideCurrRef=0
After 'for' loop: curr=0

Thus the curr outside the for loop won't change if you modify a variable of the same name inside the for loop.

Tim Jansen
Thanks Tim. Very nice explanation.
Rahul