【问题标题】:Merge the Seq of tuples and iterate over them合并元组的 Seq 并迭代它们
【发布时间】:2014-04-08 11:23:39
【问题描述】:

我有一个 Seq 元组:

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))

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

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

【问题讨论】:

    标签: scala


    【解决方案1】:

    你可以使用a ++ b合并两个Seqs:

    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))
    

    【讨论】:

      【解决方案2】:

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

      val c = b +: a
      

      【讨论】:

        猜你喜欢
        • 2017-09-26
        • 2014-03-27
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        • 1970-01-01
        相关资源
        最近更新 更多