4

Positive Case: Can get into a list

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

2.2.1
Result: [101, 104]

Negative Case: Can not do the same

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)
mert inan
  • 1,537
  • 2
  • 15
  • 26
  • 1
    In the second example, when collect is called on val, val is [99, 2]; the closure will get called first passing in 99, then again passing in 2. It doesn't make any sense to have two variables passed into the closure because at this point what collect is called on is a list of scalar values. Is there a reason to think this should work? – Nathan Hughes Apr 27 '15 at 17:40
  • I am not pushing any arguments here, I just want to understand. e.g. this works final v=1; v.collect{it+1}; this could work too, but no final l = [1,2]; l.collect{x,y->x+y}; – mert inan Apr 27 '15 at 21:29

2 Answers2

2

maybe you want

data.values().collect{x,y->x+y}
  • 1
    OP's code iterates over `data`'s key-value pairs The first key-value pair is `x:[99,2]` Then iteration occurs on **the members of each value**. The first member is `99`--but the closure provided takes two parameters--and so the exception is thrown. If OP wishes to sum each pair of numbers then I'd suggest iterating over `data`'s values summing each pair as shown above. – Martin Ahrens Apr 27 '15 at 19:47
  • 3
    An alternative is `data.collect { key, val -> val.with { x, y -> x + y } }` – tim_yates Apr 27 '15 at 20:11
  • 1
    @tim_yates Could you put your comment as an answer? – mert inan May 05 '15 at 11:34
1

An alternative is

data.collect { key, val -> val.with { x, y -> x + y } }
tim_yates
  • 167,322
  • 27
  • 342
  • 338