4 }
5 Closure1()//执行闭包,输出Helloworld
6
7 //接收一个参数
8 defClosure2={
9 Stringstr‐>printlnstr//箭头前面是参数定义,后面是执行代码,str为外部传
入的参数
10 }//如果只有一个参数可以用it代替,也可写作:
11 defClosure2={
12 printlnit
13 }
14 Closure2('Helloworld')//执行闭包,输出Helloworld
15
16 //接收多个参数
17 defClosure3={
18 Stringstr,intn‐>println"$str:$n"//参数前加$
19 }//也可以写作:
20 defClosure3={
21 str,n‐>println"$str:$n"
22 }
23 Closure3('Helloworld’,1)//执行闭包,输出Helloworld:1
24
25 //使用变量
26 defvar="Helloworld"
27 defClosure4={
28 printlnvar
29 }
30 Closure4()//执行闭包,输出Helloworld
31
32 //改变上下文
33 defClosure5={
34 printlnVar//这时还不存在
35 }
36 MyClassm=newMyClass()
37 Closure5.setDelegate(m)//改变上下文,这时Var已经有了,在执行之前改变了
38 Closure5()//执行闭包,输出Helloworld
39 classMyClass{
40 defVar='Helloworld'
41 }
42