我正在练习使用提取器:
scala> object LE {
| def unapply[A](theList: List[A]) =
| if (theList.size == 0) None
| else Some((theList.head, theList.tail))
| }
defined module LE
它适用于匹配一个元素:
scala> List(0, 1, 2) match {
| case head LE more => println(head, more)
| }
(0,List(1, 2))
但似乎不适用于匹配多个元素:
scala> List(0, 1, 2) match {
| case head LE next LE more => println(head, more)
| }
<console>:10: error: scrutinee is incompatible with pattern type;
found : List[A]
required: Int
我的列表提取器看起来非常类似于 Scala 的 Stream 提取器,可以这样使用:
val xs = 58 #:: 43 #:: 93 #:: Stream.empty
xs match {
case first #:: second #:: _ => first - second
case _ => -1
}
那么有什么区别可以阻止我的 LE 以这种方式使用呢?