中缀运算符的 Scala 匹配分解
我试图了解 Scala 中 List
的实现。 特别是,我试图了解如何使用中缀运算符编写匹配表达式,例如:
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)?
I'm trying to understand the implementation of List
s in Scala. In particular I'm trying to get my head around how you can write match expressions using an infix operator, for example:
a match {
case Nil => "An empty list"
case x :: Nil => "A list without a tail"
case x :: xs => "A list with a tail"
}
How is the match expression allowed to be x :: xs
rather than List(x, xs)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
杰伊·康拉德的回答几乎是正确的。 重要的是,某处有一个名为
::
的对象,它实现了unapply
方法,返回类型Option[(A,列表[A])]
。 因此:在
::
和List
的情况下,该对象恰好来自::
是一个扩展了的 case 类List
特征。 然而,如上面的示例所示,它根本不是一个案例类。Jay Conrad's answer is almost right. The important thing is that somewhere there is an object named
::
which implements theunapply
method, returning typeOption[(A, List[A])]
. Thusly:In the case of
::
andList
, this object happens to come out of the fact that::
is a case class which extends theList
trait. However, as the above example shows, it doesn't have to be a case class at all.我相信 :: 实际上是一个类(它是 List 的子类),所以
x :: xs
基本上等同于List(x, xs)
。您可以对具有运算符名称的其他案例类执行此操作。 例如:
I believe :: is actually a class (which is a subclass of List), so saying
x :: xs
is mostly equivalent toList(x, xs)
.You can do this with other case classes that have operator names. For instance:
回答这个问题:
(Scala 编程,第一版,第 331 页)
另请参阅 scala 案例类问题
To answer this question:
(Programming in Scala, 1st ed., p. 331)
See also scala case classes questions