1. 闭包 closures
a) 可执行代码段
def range = 1..3 // 定义一个 Range
range.each() { num -> // num 是闭包的参数
println num // 使用参数
}
// 输出结果,表示闭包的这个代码段被执行了 3 次。
1
2
3
b) it 的用法
def range = 1..3
range.each(){// 只有一个参数,则可以省略
println it // 一个参数,使用 it
println it.class
}
2. 流程控制语法 Control structures
a) if else, while, switch, and try-catch-finally
b) if 和 null 。可以将 null 和 false 等同,非 null 和 true 等同。
if (false) { // 传统 java 的 if 只能判断 true 或 false 。
assert false // 该语句会抛出 AssertionError 异常
} else {
assert true
}
if (null) { // Groovy 的 if 还可以判断 null 和非 null 。
assert false
} else {
assert true
}
c) switch case 的语法。
i. Java 只对 int,byte,char 支持
ii. Groovy 提供对 String 的支持
def x = 'AB'
switch(x) {
case 'AB': println 'AB'; break;
case 'CD': println 'CD'; break;
default: println 'Default'
}
// 输出结果:
AB
d) in 的语法。可用于 Range 和 List
def list = 0..4
for (j in list) {
assert j == list[j]
}