Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy expand tuple/map to arguments

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)

like image 427
Queequeg Avatar asked Nov 19 '12 07:11

Queequeg


2 Answers

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.

like image 171
Arturo Herrero Avatar answered Sep 18 '22 20:09

Arturo Herrero


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

like image 25
tim_yates Avatar answered Sep 17 '22 20:09

tim_yates