从 Tuple2 数组创建 case class 对象的最简单方法是什么?
What's the easiest way to create a case class objects from an Array of Tuple2?
我有两个数组,我想将它们组合起来创建一个 Array[Item]
。 Item
是一个案例 class。这是一个例子:
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:_*)
您可以 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))
我有两个数组,我想将它们组合起来创建一个 Array[Item]
。 Item
是一个案例 class。这是一个例子:
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:_*)
您可以 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))