开发者

What does the safe navigation operator look like for closures in Groovy?

开发者 https://www.devze.com 2023-03-24 10:52 出处:网络
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)?

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')
0

精彩评论

暂无评论...
验证码 换一张
取 消