Groovy中闭包的安全导航操作符是什么样子的?

Groovy中闭包的安全导航操作符是什么样子的?,groovy,Groovy,考虑以下示例: def c = { println it } c("hello, world!") 此脚本应无错误地执行。但如果c从未定义过(即null),该怎么办 此脚本将出现运行时错误。在这种情况下,是否有安全的导航操作员可供使用,或者我是否陷入了if状态 def c = { println it } c?.("hello, world!") 当c不为null时,此脚本似乎不起作用。您应该能够使用较长的形式,即: c?.call( 'hello world?' ) 根据您的需求,您可以

考虑以下示例:

def c = { println it }
c("hello, world!")
此脚本应无错误地执行。但如果c从未定义过(即null),该怎么办

此脚本将出现运行时错误。在这种情况下,是否有安全的导航操作员可供使用,或者我是否陷入了if状态

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

当c不为null时,此脚本似乎不起作用。

您应该能够使用较长的形式,即:

c?.call( 'hello world?' )

根据您的需求,您可以使用no-op闭包而不是null

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

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