Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created December 10, 2015 05:52
Show Gist options
  • Save Allan-Gong/986dc18b70f0e0bc4900 to your computer and use it in GitHub Desktop.
Save Allan-Gong/986dc18b70f0e0bc4900 to your computer and use it in GitHub Desktop.
Demonstration of closure in Scala
package otherscope {
class Foo {
// a method that takes a function and a string, and passes the string into
// the function, and then executes the function
def exec(f:(String) => Unit, name: String) {
f(name)
}
}
}
object ClosureExample extends App {
var hello = "Hello"
def sayHello(name: String) { println(s"$hello, $name") }
// execute sayHello from the exec method foo
val foo = new otherscope.Foo
foo.exec(sayHello, "Al")
// change the local variable 'hello', then execute sayHello from
// the exec method of foo, and see what happens
hello = "Hola"
foo.exec(sayHello, "Lorenzo")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment