【问题标题】:how to use closure for passing multiple argument in closure in groovy如何使用闭包在groovy的闭包中传递多个参数
【发布时间】:2021-10-23 12:48:35
【问题描述】:

下面是我的 groovy 代码,我想在 groovy 的闭包中传递多个参数

package com.test.demo

def str = {'Yash' , 'deep'}
def merged = { println "$str world"}

merged.call()

这段代码给了我一个错误请任何人给我一个解决方案我如何在 groovy 的闭包中传递多个参数

【问题讨论】:

  • 你到底想做什么?你遇到了什么错误?如果你需要在闭包中有参数,你声明它们:{param1, param2 -> ...code here...}
  • 什么错误?您已经在这里捕获str - 通过通常意味着您通过call 传递它。你真的要在这里打印[Yash, deep] world吗?
  • @cfrick 是的,我想打印 [Yash,deep] 世界
  • 您提供的代码在 groovy Web 控制台中工作。你看到了什么错误?
  • @tim_yates 由于示例中的语法错误,我已经编辑了问题。但我猜 OP 真的想要关闭,因此恢复了编辑。

标签: groovy closures


【解决方案1】:

你的原始代码有两个问题:

{ 'Yash' , 'deep' } 并不意味着返回一个数组,但这会 给你一个错误:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/tmp/x.groovy: 2: Unexpected input: ',' @ line 2, column 19.
   def str = {'Yash' , 'deep'}

因此,您必须将该闭包重写为:

{['Yash' , 'deep']}

(注意[]

接下来,如果你像这样打印闭包,你会得到参考 打印 - 所以你需要调用它。

def merged = { println "${it()} world"}
def str = {['Yash' , 'deep']}
merged(str)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多