File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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\n frnr.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
+ */
You can’t perform that action at this time.
0 commit comments