2017-01-10 54 views
0

這可能是一個微不足道的問題,但我對Groovy比較陌生。Groovy-rific一次創建多個對象的方法?

說我有一個簡單的POJO:

class Ident { 
    String a, 
    String b, 
    String c 
} 

接下來,我有另一個類這樣的功能:

void select(Ident ... idents) { 
    // do something for each ident 
} 

現在,我只是在做Java的方式:

blah.select(new Ident(a1, b1, c1), 
      new Ident(a2, b2, c2), 
      ... 
      new Ident(aN, bN, cN)) 

很顯然,我已經縮短了名。

我只是想知道是否有一種Groovy-ier方式來重寫這個。或者是這樣嗎?

我知道有一個基於地圖的構造函數,但我認爲它更加冗長。

回答

1

可以使用傳播運營商名單上,如果你有一個構造函數的所有參數的個數以正確的順序,也可以間接地使用地圖的構造函數:

import groovy.transform.TupleConstructor 

@TupleConstructor // add constructor Ident(a,b,c) 
class Ident { 
    String a 
    String b 
    String c 
} 

def argLists = [['a1', 'b1', 'c1'], ['a2', 'b2', 'c2']] 

argLists.collect { new Ident(*it) } //spread 

argLists.collect { it as Ident } // list coercion 

argLists.collect { 
    def map = [['a', 'b', 'c'], it].transpose().collectEntries() 
    new Ident(map) // map constructor 
} 

argLists.collect { 
    [['a', 'b', 'c'], it].transpose().collectEntries() as Ident // map coercion 
} 
+0

真棒,謝謝! – aberrant80