合并元组的Seq并迭代它们

时间:2014-04-08 11:23:39

标签: scala

我有一个Seq of tuples:

scala> val a = Seq[(Int, String)]((1, "111"), (2, "222"))
a: Seq[(Int, String)] = List((1,111), (2,222))

scala> val b = Seq[(Int, String)]((4, "444"))
b: Seq[(Int, String)] = List((4,444))

我想在迭代中合并它们(追加):

scala> val c = b :+ a
c: Seq[Equals] = List((4,444), List((1,111), (2,222)))

显然,我收到了错误:

scala> c.foreach { x =>
     | println(x._2)
     | }

<console>:12: error: value _2 is not a member of Equals
          println(x._2)

这也没有帮助:

val d = c.asInstanceOf[Seq[(Int, String)]]
res14: Seq[(Int, String)] = List((4,444), List((1,111), (2,222)))


scala> d.getClass
res15: Class[_ <: Seq[(Int, String)]] = class scala.collection.immutable.$colon$colon


scala> d.foreach { x =>
     | println(x._2)
     | }
444
java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to scala.Tuple2

2 个答案:

答案 0 :(得分:2)

您可以使用a ++ b合并两个Seq s:

val a = Seq[(Int, String)]((1, "111"), (2, "222"))
a: Seq[(Int, String)] = List((1,111), (2,222))

val b = Seq[(Int, String)]((4, "444"))
b: Seq[(Int, String)] = List((4,444))

a ++ b
res0: Seq[(Int, String)] = List((1,111), (2,222), (4,444))

答案 1 :(得分:1)

实际上你使用了错误的运算符 - 它应该是

val c = b +: a