2011-07-29 17 views
2

请看下面的例子:安全导航运算符在Groovy中的闭包是什么样的?

def c = { println it } 
c("hello, world!") 

这个脚本应该执行没有错误。但是如果c从未定义过(如null)呢?

def c = null 
c("hello, world!") 

此脚本会产生运行时错误。在这种情况下是否有安全的导航操作员,或者我坚持if条件?

def c = { println it } 
c?.("hello, world!") 

当c不为空时,该脚本看起来不起作用。

回答

5

您应该能够使用更长的call()形式,即:

c?.call('hello world?') 
0

根据您的需求,您可以只使用一个无操作关闭而不是空值。

final c = { println it } 
c('hello world') 


final c = {} 
c('hello world') 
相关问题