What does the safe navigation operator look like for closures in Groovy?
Consider the following example:
def c = { println it }
c("hello, world!")
This script should execute without error. But what if c were never defined (ie nu开发者_如何学Cll)?
def c = null
c("hello, world!")
This script would have a runtime error. Is there a safe navigation operator for use in this case or am I stuck with the if condition?
def c = { println it }
c?.("hello, world!")
This script doesn't appear to work when c is not null.
You should be able to use the longer call()
form, ie:
c?.call( 'hello world?' )
Depending on your requirements you could just use a no-op closure instead of null.
final c = { println it }
c('hello world')
final c = {}
c('hello world')
精彩评论