【问题标题】:Groovy's inconsistent destructuring / decomposition on lists?Groovy 在列表上的解构/分解不一致?
【发布时间】:2015-07-06 06:45:59
【问题描述】:

正例:可以进入列表

groovy> println GroovySystem.version  
groovy> final data1 = [[99,2] , [100,4]] 
groovy> data1.collect{x,y->x+y} 

2.2.1
Result: [101, 104]

否定案例:不能这样做

groovy> println GroovySystem.version  
groovy> final data = [x:[99,2] , y:[100,4]] 
groovy> data.collect{key,  val-> 
groovy>    val.collect{x,y->x+y} 
groovy> }.flatten() 

2.2.1
Exception thrown

groovy.lang.MissingMethodException: No signature of method: ConsoleScript80$_run_closure1_closure2.doCall() is applicable for argument types: (java.lang.Integer) values: [99]
Possible solutions: doCall(java.lang.Object, java.lang.Object), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object)
    at ConsoleScript80$_run_closure1.doCall(ConsoleScript80:5)
    at ConsoleScript80.run(ConsoleScript80:4)

【问题讨论】:

  • 第二个例子中,在val上调用collect时,val为[99, 2];闭包将被调用,首先传入 99,然后再次传入 2。将两个变量传递给闭包没有任何意义,因为此时调用的 collect 是一个标量值列表。有理由认为这应该有效吗?
  • 我不是在这里提出任何论据,我只是想了解一下。例如这工作最终 v=1; v.收集{it+1};这也可以,但没有最终的 l = [1,2]; l.collect{x,y->x+y};

标签: groovy closures decomposition destructuring


【解决方案1】:

也许你想要

data.values().collect{x,y->x+y}

【讨论】:

  • OP的代码迭代data的键值对第一个键值对是x:[99,2]然后迭代发生在每个值的成员上。第一个成员是99——但提供的闭包有两个参数——因此抛出异常。如果 OP 希望对每对数字求和,那么我建议迭代 data 的值,对每对数字求和,如上所示。
  • 另一种选择是data.collect { key, val -> val.with { x, y -> x + y } }
  • @tim_yates 你能把你的评论作为答案吗?
【解决方案2】:

另一种选择是

data.collect { key, val -> val.with { x, y -> x + y } }

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2014-09-01
    • 2017-10-23
    • 2016-09-03
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2020-10-02
    • 2019-02-16
    相关资源
    最近更新 更多