【问题标题】:What does the safe navigation operator look like for closures in Groovy?Groovy 中闭包的安全导航操作符是什么样的?
【发布时间】:2011-07-29 21:04:43
【问题描述】:

考虑以下示例:

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

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

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

此脚本会出现运行时错误。在这种情况下是否可以使用安全导航运算符,或者我是否坚持 if 条件?

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

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

【问题讨论】:

    标签: groovy


    【解决方案1】:

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

    c?.call( 'hello world?' )
    

    【讨论】:

      【解决方案2】:

      根据您的要求,您可以只使用无操作闭包而不是 null。

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


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

      【讨论】:

        猜你喜欢
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-25
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        • 2012-04-27
        相关资源
        最近更新 更多