scala案例类问题
我有两个关于“::”案例类的问题。
:: 可以用作
case head :: tail => ...
它是如何工作的?意思是,Scala 用于将 List 实例与 :: case 类进行匹配的流程到底是什么?鉴于我有一个类 MyClass,带有运算符 op,我可以创建一个名为 op 的案例类,我可以将其用作:
case foo op bar => ....
?
I have two questions regarding the '::' case class.
:: can be used as
case head :: tail => ...
How does it work? Meaning, what is exactly the flow that Scala uses to match a List instance with the :: case class? Given that I have a class MyClass, with operator op, can I create a case class named op that I can use as:
case foo op bar => ....
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Scala 编程的第 301 页有详细介绍,关于
List 上的模式匹配s.
It's detailed in page 301 of Programming in Scala, About pattern matching on
List
s.实际上, :: 是一个案例类这一事实只解决了一半问题。它在模式匹配中起作用的原因是,有一个对象 :: 的提取器,它是在定义案例类时自动生成的。方便的是, ::.unapply 返回一个 List,因为 :: 扩展了 List。但是,如果您想对列表使用相同的技巧,您将无法扩展列表,因为它是最终的。您可以做的是使用适当的 unapp 方法定义一个对象,该方法具有预期的返回签名。例如,要匹配列表的最后一个元素,您可以执行以下操作:
提取器必须返回一个选项,其中包含两个解构元素的元组。
Actually, the fact that :: is a case class is only half of the answer. The reason this works in pattern matching is that there is an extractor for object ::, which is generated automatically when a case class is defined. Conveniently, ::.unapply returns a List, because :: extends List. If you want to use the same trick for Lists, though, you won't be able to extend List, because it's final. What you can do is define an object with the appropriate unapply method, which has the expected return signature. For instance, to match the last element of a list, you can do:
The extractor must return an Option, which contains a tuple of the two deconstructed elements.