我有一个简单的代码,可以将元素与长度为26的Seq匹配。
test("Seq Pattern matching") {
val x = 1 to 26
x match {
case Seq(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) => println(a)
}
}
它将调用Seq.unapplySeq
方法来解构Seq对象x
,但令我惊讶的是,该代码会导致编译错误:
Error:(82, 12) too many arguments for unapply pattern, maximum = 22
case Seq(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) => println(a)
在unapplySeq方法中,它与具有22个字段限制的case类或元组没有任何关系。
所以,我想问为什么会发生错误(为什么case class / tuple字段限制导致此问题)
我正在使用Scala 2.11.8
答案 0 :(得分:0)
我弄清楚了unapplySeq
方法背后的情况,它涉及元组
对于
(1 to 10) match {
case Seq(a, b, c, d, e, f, g, h, i, j) => (a, b, c);
case _ => (1, 2, 3);
}
类似:
scala.Predef.intWrapper(1).to(10) match {
case scala.collection.Seq.unapplySeq[Int](<unapply-selector>) <unapply> ((a @ _), (b @ _), (c @ _), (d @ _), (e @ _), (f @ _), (g @ _), (h @ _), (i @ _), (j @ _)) => scala.Tuple3.apply[Int, Int, Int](a, b, c)
case _ => scala.Tuple3.apply[Int, Int, Int](1, 2, 3)
}