2010-05-31 8 views
2
def foo(map, name) { 
    println(map) 
} 

foo("bar", hi: "bye") 

imprimeraopérateur de splat dans groovy?

[hi:bye] 

Maintenant, j'ai une carte précédente que je veux transmettre à toto. Dans le code pseudo, quelque chose comme:

def otherMap = [hi: "world"] 
foo("bar", hi: "bye", otherMap*) 

Alors qu'il imprime

[hi:world] 

Cela ne fonctionne pas bien sûr.

Aussi, en essayant de passer juste la carte mélange l'ordre des arguments:

def otherMap = [hi: "world"] 
foo("bar", otherMap) 

imprimera

bar 

Comment puis-je résoudre ce problème?

+1

Comment voulez-vous 'foo ("bar", otherMap)' imprimer autre chose que 'bar'? Vous imprimez le premier paramètre. – Geo

Répondre

7

Vous recherchez l'opérateur spread-map.

def foo(map, name) { 
    println(map) 
} 

foo("bar", hi: "bye") 

def otherMap = [hi: "world"] 
foo("bar", hi: "bye", *:otherMap) 
foo("bar", *:otherMap, hi: "bye") 

impressions:

["hi":"bye"] 
["hi":"world"] 
["hi":"bye"] 
0

Je ne suis pas sûr de ce que vous voulez exactement à réaliser, voici donc plusieurs possibilités:

Si vous souhaitez ajouter le contenu de la deuxième carte à la première carte, l'opérateur leftShift est la voie à suivre :

def foo(name, map) { 
    println(map) 
} 

def otherMap = [hi: "world"] 
foo("bar", [hi: "bye"] << otherMap) 

Si vous souhaitez accéder à un paramètre via son nom utiliser une carte:

def foo(Map args) { 
    println args.map 
} 

def otherMap = [hi: "world"] 
foo(name:"bar", first:[hi: "bye"], map:otherMap) 

Si vous voulez imprimer ou seulement le dernier paramètre u se varargs:

def printLast(Object[] args) { 
    println args[-1] 
} 

def printAll(Object[] args) { 
    args.each { println it } 
} 

def printAllButName(name, Map[] maps) { 
    maps.each { println it } 
} 

def otherMap = [hi: "world"] 
printLast("bar", [hi: "bye"], otherMap) 
printAll("bar", [hi: "bye"], otherMap) 
printAllButName("bar", [hi: "bye"], otherMap)