Groovy expand tuple / map for arguments

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

In Python, this is possible, for example. Extension of tuples in arguments

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

I want to write smt as m(*map)

+8
parameter-passing arguments groovy
source share
3 answers

the distribution operator (*) is used to split the list into separate items. This can be used to invoke a method with several parameters, and then propagate the list to the values โ€‹โ€‹for the parameters.

List (lists in Groovy are most closely related to tuples in Python 1 , 2 ):

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

Map

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

The import point is that you pass arguments by position.

+7
source share

The best I can think of right now:

 @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, when calling the function / constructor, the map display order is executed, and not the key names.

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

+1
source share
  mmap = { 'a':1, 'b':2 } def m( a, b ): return a+b print m( **mmap ) 

thirty

3

-one
source share

All Articles