Scala 函数式与面向对象的融合
如果您试图向某人解释 Scala 如何完美地融合了函数式技术和面向对象技术,您会使用哪个示例?
If you were trying to explain someone how nicely Scala blends functional and object-oriented techniques, which example would you use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我的Scala的诱惑谈话中,我以一个 Actor 的例子结束它使用函数式模式匹配来确定接收到的消息的“种类”,并使用面向对象样式的多态调度来处理消息“种类”之一(要绘制的几何形状)。它从幻灯片 76 开始。
In my canned Seductions of Scala talk, I end with an Actor example that uses functional-style pattern matching for determining the "kind" of message received and object-oriented-style polymorphic dispatch for one of the message "kinds" (a geometric shape to draw). It starts around slide 76.
Actor API 是一个很好的例子,展示了如何结合使用两种方法的优势。您还可以查看 Map 的实现,以及它子类化 Function1 的方式
The actor API is a great example of how the strengths of both approaches are used together. You can also look at the implementation of Map, and the way that it subclasses Function1
Martin 指出
PartialFunction
作为 OO/FP 综合唯一实现的那种事情的信号示例。具体来说,您可以将其视为一个函数并直接调用它,冒着发生异常的风险,或者您可以先询问它是否可能抛出给定的某个参数。前者是一流函数的自然结果,您希望在任何自封的函数语言中看到它;后者是一流函数的自然结果。后者可以说是一些特别的东西。Martin has pointed to
PartialFunction
as a signal example of the kind of thing that the OO/FP synthesis uniquely enables. Specifically, you can treat it as a function and just call it, running the risk of an exception, or you can ask it first whether it's likely to throw given some argument. The former is a natural consequence of first-class functions, and you'd expect to see it in any self-styled functional language; the latter is arguably something special.