演员 Christopher Walken 曾在周末夜现场(Saturday Night Live)上演了一出喜剧,他说要“拳打南山猛虎、脚踢北海苍龙”。同样,Groovy 团队也听到了人们的呼声,要求加入更多的特性,就在最近他们发布了该获得大奖的语言的 1.6 版。其发布声明宣称该版本拥有众多的新特性,包括:
- 运行时性能的巨大改进
- 多路赋值——if/else 和 try/catch 块中可选的 return 语句
- AST 转换及各种转换注解,如 @Singleton、@Lazy、@Immutable、@Delegate 及助手
- Grape 模块和依赖系统及其 @Grab 转换
- 各种改进的 Swing builder,这要归功于 Swing / Griffon( http://griffon.codehaus.org )团队
- 几个 Swing 控制台的改进
- 集成 JMX builder
- 内建的 JSR-223 脚本引擎
- 改进的各种元编程,像是 EMC DSL、甚至是针对 POJO 的单实例元类及运行时掺元(mixin)
该版本的一个主要关注点就是性能,Groovy 团队说已经将性能提高了150% 到460%。另一个特性就是对 JMX builder 提供了官方的集成,这又一次证明了社区对 Groovy 改进的巨大推动力。
以下示例展示了该版本的几个新特性,包括多路赋值及 AST 转换。
// this class' properties are immutable once the object is constructed<br></br>
@Immutable final class ServerConfig {<br></br>
String url<br></br>
int port<br></br>
}<p>
def getServerInfo() {</p><br></br>
['http://home.net', 8080]<br></br>
}<p>
// attempts to set a property on an Immutable object</p><br></br>
def setUrl(config, newUrl) {<br></br>
try {<br></br>
config.url = newUrl<br></br>
}<br></br>
catch (ReadOnlyPropertyException ex) {<br></br>
ex<br></br>
}<br></br>
}<p>
// multiple assignment</p><br></br>
def (url, port) = getServerInfo()<p>
assert url == 'http://home.net'</p><br></br>
assert port == 8080<p>
def config = new ServerConfig(url, port)</p><p>
assert config.url == url</p><br></br>
assert config.port == port<p>
// try to change the property on the Immutable object</p><br></br>
def result = setUrl(config, 'www.google.com')<p>
// verify the property change failed</p><br></br>
assert result instanceof ReadOnlyPropertyException<br></br>
上面的示例展示了 @Immutable AST 转换如何以简单的方式创建只读对象。该示例还介绍了新的“多路赋值”特性。请查看 Groovy 用户指南来了解关于 AST 转换的更多信息,上面的示例只介绍了 @Immutable 转换。
既然已经对 Groovy 1.6 有了一个大概的了解,为何不看看 Groovy 1.6 的新特性这篇文章呢? 这是 Groovy 项目经理 Guillaume LaForge 专门为 InfoQ 撰写的关于 Groovy 1.6 的文章,该文并不是泛泛而谈,而是深入剖析了 Groovy 1.6 的新特性。Guillaume 介绍了所有的新特性并提供了大量代码示例来阐述这些新功能。
查看英文原文: Just the Cure, More Groovy




