Skip to content

Instantly share code, notes, and snippets.

@archena
Created January 16, 2014 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archena/8460281 to your computer and use it in GitHub Desktop.
Save archena/8460281 to your computer and use it in GitHub Desktop.
Some silly loops and perfectly sensible capture semantics. Based on an example of Erik Meijer, translated from c#. Normal people use the `for(i <- x)` style loop in Scala.
def loopA = {
// 0 1 2 3
var i = 0
while(i < 4) {
print(i)
i = i + 1
}
println("")
}
def loopB = {
// 4 4 4 4
var i = 0
val closures = new Array[() => Unit](4)
while(i < 4) {
closures(i) = () => print(i)
i = i + 1
}
for(c <- closures) c()
println("")
}
def loopC = {
// 0 1 2 3
var i = 0
val closures = new Array[() => Unit](4)
while(i < 4) {
val j = i
closures(i) = () => print(j)
i = i + 1
}
for(c <- closures) c()
println("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment