我试图了解 List
的实现在 Scala 中。特别是,我试图了解如何使用中缀运算符编写匹配表达式,例如:
a match {
case Nil => "An empty list"
case x :: Nil => "A list without a tail"
case x :: xs => "A list with a tail"
}
如何允许匹配表达式为
x :: xs
而不是 List(x, xs)
?
最佳答案
杰伊康拉德的回答几乎是正确的。重要的是某处有一个名为 ::
的对象。它实现了 unapply
方法,返回类型 Option[(A, List[A])]
.因此:
object :: {
def unapply[A](ls: List[A]): Option[(A, A)] = {
if (ls.empty) None
else Some((ls.head, ls.tail))
}
}
// case objects get unapply for free
case object Nil extends List[Nothing]
在
::
的情况下和 List
,这个对象恰好来自::
是扩展 List
的案例类特征。但是,如上例所示,它根本不必是 case 类。
关于list - 中缀运算符上的Scala匹配分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1022218/