Created
December 10, 2015 05:52
-
-
Save Allan-Gong/986dc18b70f0e0bc4900 to your computer and use it in GitHub Desktop.
Demonstration of closure in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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