11

Is it possible to expand a map to a list of method arguments

In Python it is possible, eg. Expanding tuples into arguments

I have a def map = ['a':1, 'b':2] and a method def m(a,b)

I want to write smt like m(*map)

4

3 に答える 3

10

The spread operator (*) is used to tear a list apart into single elements. This can be used to invoke a method with multiple parameters and then spread a list into the values for the parameters.

List (lists in Groovy are closest related with tuples in Python1,2):

list = [1, 2]
m(*list)

Map:

map = [a: 1, b: 2]
paramsList = map.values().toList()
m(*paramsList)

An importan point is that you pass the arguments by position.

于 2012-11-19T10:45:01.620 に答える
1

The best I can currently think of is:

@groovy.transform.Canonical
class X {
  def a
  def b

  def fn( a, b ) {
    println "Called with $a $b"
  }
}

def map = [ a:1, b:2 ]

def x = new X( map.values().toList() )

x.fn( map.values().toList() )

However, that takes the order of the map, and not the names of the keys into consideration when calling the function/constructor.

You probably want to add a function/constructor that takes a Map, and do it that way

于 2012-11-19T09:36:12.150 に答える
-3
   mmap = { 'a':1, 'b':2 }

   def m( a, b ):
       return a+b
   print m( **mmap )

30

3

于 2012-11-19T09:16:52.650 に答える