2017-02-16 44 views
2

我有兩個陣列,我喜歡合併並創建一個Array[Item]Item是一個案例類。這裏有一個例子:從Tuple2數組創建案例類對象的最簡單方法是什麼?

case class Item(a: String, b: Int) 

val itemStrings = Array("a_string", "another_string", "yet_another_string") 

val itemInts = Array(1, 2, 3) 

val zipped = itemStrings zip itemInts 

目前我採用如下方案來解決,但我不知道是否有其他的可能性這個...

val itemArray = zipped map { case (a, b) => Item(a, b) } 

,帶出我想要的東西:

itemArray: Array[Item] = Array(Item(a_string, 1), Item(another_string, 2), Item(yet_another_string, 3)) 

我也試過這個,但它不適用於一系列元素:

(Item.apply _).tupled(zipped:_*) 

Item.tupled(zipped:_*) 

回答

3

您可以map在與Item.tupled數組:

zipped.map(Item.tupled) 

scala> zipped.map(Item.tupled) 
res3: Array[Item] = Array(Item(a_string,1), Item(another_string,2), Item(yet_another_string,3)) 
相關問題