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)
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)
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.
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
mmap = { 'a':1, 'b':2 }
def m( a, b ):
return a+b
print m( **mmap )
30
3