What are the output results of the following program?
Package pz007object pz007 extends app{ import collection.mutable.buffer import collection. seq val funcs1 = buffer[() => int] () //create empty arraybuffer val funcs2 = buffer[() => int] () { val values = seq (100, 110, 120) // create a list buffer var j = 0 for (i <- 0 until values.length) { funcs1 += (() => values (i) funcs2 += () => values (j)) j += 1 } } funcs1 foreach {f1 => println (F1 ())} fUncs2 foreach {f2 => println (F2 ())}}
Explain:
The first thing to do is immediately how the for expression is expanded into a foreach function. The i in the for expression is defined as a number of Val, as arguments to the parameters of the foreach function. So the function in funcs1 get I actually is 0, 1, 2
Conversely, the function in funcs2 gets the J always variable J, and the last value of the variable J is 3.
Scala Fun Question 7