val x = for(i <- 1 to 3) yield i
x match {
case 1 :: rest => ... // compile error
}
构造函数不能实例化为预期的类型;找到:集合.immutable。::B必需: scala.collection.immutable.IndexedSeqInt
这是与MatchError when match receives an IndexedSeq but not a LinearSeq相同的问题。
问题是,怎样做才是正确的?到处添加.toList
似乎并不正确。如果创建一个自己的提取器来处理每个Seq
(如另一个问题的答案中所述),如果每个人都这样做,将会导致混乱……
我想问题是,为什么我不能影响序列理解的返回类型,或者:为什么标准库中没有这样一个通用的Seq
提取器?
发布于 2012-07-16 19:20:10
你可以对任何序列进行模式匹配:
case Seq(a, b, rest @ _ *) =>
例如:
scala> def mtch(s: Seq[Int]) = s match {
| case Seq(a, b, rest @ _ *) => println("Found " + a + " and " + b)
| case _ => println("Bah")
| }
mtch: (s: Seq[Int])Unit
然后,这将匹配任何超过(或等于)2个元素的序列
scala> mtch(List(1, 2, 3, 4))
Found 1 and 2
scala> mtch(Seq(1, 2, 3))
Found 1 and 2
scala> mtch(Vector(1, 2))
Found 1 and 2
scala> mtch(Vector(1))
Bah
发布于 2018-11-22 23:17:54
REPL中的Vector还有一个解决方案:
Vector() match {
case a +: as => "head + tail"
case _ => "empty"
}
res0: String = "empty"
Vector(1,2) match {
case a +: as => s"$a + $as"
case _ => "empty" }
res1: String = 1 + Vector(2)
https://stackoverflow.com/questions/11503033
复制相似问题