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

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

將打印splat運算符在groovy中?

[hi:bye] 

現在我有一個以前的地圖,我想一起FOO通過。在僞代碼,類似:

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

所以它打印

[hi:world] 

當然,這是行不通的。

此外,試圖通過剛剛地圖混合參數的順序:

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

將打印

bar 

我該如何解決這個問題?

+1

你怎麼能指望'FOO( 「酒吧」,otherMap)'打印的東西比'bar'別的嗎?您正在打印第一個參數。 – Geo 2010-05-31 09:43:24

回答

7

您正在尋找擴散圖運算符。

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

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

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

打印:

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

我不知道你到底想達到什麼,所以這裏有幾種可能性:

如果你想從第二映射到第一張地圖添加內容時,leftShift運營商是要走的路:

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

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

如果你想通過訪問其名稱的參數使用地圖:如果你要打印所有或只有最後參U

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

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

se可變參數:

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)