注解定义
事实上,“多路赋值是增加的唯一一个语法”这种说法并不完全正确。从Groovy 1.5开始就已经支持注解定义语法了,但我们并没有完全实现这个特性。好在现在已经实现了,它对Groovy所支持的所有Java 5特性进行了包装,比如静态导入、泛型、注解和枚举,这使得Groovy成为唯一一个支持Java 5所有特性的JVM动态语言,这对于与Java的无缝集成非常关键,对那些依赖于注解、泛型等Java 5特性的企业框架来说也很重要,比如JPA、EJB3、Spring及TestNG等等。
if/else与try/catch/finally块中可选的返回语句
如果if/else与try/catch/finally块是方法或语句块中最后的表达式,那么他们也可以返回值了。无需在这些块中显式使用return关键字,只要他们是代码块中最后的表达式就行。
尽管省略了return关键字,但下面的代码示例中的方法仍将返回1。
1 def method() {
2
3 if (true) 1 else 0
4
5 }
6
7 assert method() == 1
2
3 if (true) 1 else 0
4
5 }
6
7 assert method() == 1
对于try/catch/finally块来说,最后计算的表达式也是返回的值。如果try块中抛出了异常,那么catch块中的最后一个表达式就会返回。注意,finally块不会返回任何值。
1 def method(bool) {
2
3 try {
4
5 if (bool) throw new Exception("foo")
6
7 1
8
9 } catch(e) {
10
11 2
12
13 } finally {
14
15 3
16
17 }
18
19 }
20
21 assert method(false) == 1
22
23 assert method(true) == 2
2
3 try {
4
5 if (bool) throw new Exception("foo")
6
7 1
8
9 } catch(e) {
10
11 2
12
13 } finally {
14
15 3
16
17 }
18
19 }
20
21 assert method(false) == 1
22
23 assert method(true) == 2