我有两个我喜欢组合并创建Array[Item]
的数组。Item
是一个案例类。这是一个示例:
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:_*)
您可以使用Item.tupled
:
map
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))