Skip to content

Commit 51bab98

Browse files
committed
Closures in Scala
1 parent 1230a84 commit 51bab98

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Functions/Closures.scala

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/***
2+
* Closures are functions that close around the environment.
3+
* Closures are used to make up the functions from environment
4+
* It is good practice to enclose around something stable. e.g. val
5+
*/
6+
7+
class FunctionRunner(x:Int)
8+
{
9+
def runFunction(y:Int => Int) = y(x)
10+
}
11+
12+
object Closures extends App{
13+
val m = 200 //m is an outside variable. If m is of type var, function will change its value
14+
val f = (x:Int) => x + m //define function here
15+
16+
val frnr = new FunctionRunner(100)
17+
println("frnr.runFunction(f): " + frnr.runFunction(f))
18+
19+
// using closure with a variable
20+
var n = 200
21+
val f2 = (x:Int) => x + n
22+
println("frnr.runFunction(f2): " + frnr.runFunction(f2))
23+
n = 300
24+
println("After n = 300\nfrnr.runFunction(f2): " + frnr.runFunction(f2))
25+
}
26+
27+
/**
28+
Sample Output
29+
frnr.runFunction(f): 300
30+
frnr.runFunction(f2): 300
31+
After n = 300
32+
frnr.runFunction(f2): 400
33+
34+
*/

0 commit comments

Comments
 (0)