scala - polymorphic dispatch from object-oriented programming with pattern matching
问题描述
There is this below paragraph from one of the book(book details below)I am reading for Scala. I am not able to understand what the author is trying to say. Can anyone provide more details about this?.
Book Details:
Programming Scala, 2nd Edition By Dean Wampler, Alex Payne. I am reading this book from O’Reilly Safari books app so I do not have the page number. This is from the very end of the chapter “Chapter 1 Zero to Sixty: Introducing Scala”
About Me: I am working with Scala 2.11 for around 1.5 years and have some moderate experience of working with it. I would rate myself as 3/5 in my proficiency level. I am trying to read the book mentioned to improve my knowledge.
Snippet from the book: “Hence, we have combined polymorphic dispatch from object-oriented programming with pattern matching, a workhorse of functional programming. This is one way that Scala elegantly integrates these two programming paradigms.”</p>
解决方案
尽管您可能希望下次在您的问题中指定此信息,但我假设您谈论的是从第 19 页开始的“并发的味道”部分,更准确地说是第 27 页的结尾段落。
多态分派,也称为动态分派,是面向对象编程(OOP)的主要优点之一。它允许选择一个方法的实现来动态执行,也就是说在运行时。
模式匹配是你可以在 Scala 等函数式语言中做的巧妙的事情,即根据一个或多个参数遵循的模式来改变方法的执行(有点像一个增压的 case 语句,如果标签可能很多更详细并涉及其论点的类型和其他特征!)。
Akka 框架(提供 Scala API)用于获得简单的并发性,并且基于参与者模型。Actor 相互发送消息,这些消息以异步、非阻塞的方式进行处理。
现在我们已经掌握了基础知识,让我们检查一下该段落所引用的代码:
def receive = {
case s: Shape =>
s.draw(str => println(s"ShapesDrawingActor: $str"))
sender ! Response(s"ShapesDrawingActor: $s drawn")
case Exit =>
println(s"ShapesDrawingActor: exiting...")
sender ! Finished
case unexpected =>
val response = Response(s"ERROR: Unknown message: $unexpected"
println(s"ShapesDrawingActor: $response")
sender ! response
}
Akka 中一个 Actor 的接收方法在每次接收到另一个 Actor 的消息时都会被调用。消息可以是任何类(例如 String、Double 甚至您自己的类)。发生这种情况时,首先使用模式匹配(参见案例标签?)根据消息的类型(类)执行代码。
如果 actor 收到 Shape 类的消息,Shape 案例标签之后的第一行将调用 Shape 实例的 draw 方法。如果运行时消息的类实际上是Shape的子类(它继承自Shape),则使用动态(多态)分辨率来决定调用哪个draw方法的实现。
我们可以只使用这两种技术中的一种来获得相同的结果,但代价是不得不编写更多不必要的代码。
推荐阅读
- python - Django 静态文件 3.1 的问题
- python - 通过迭代将文本附加到列表中
- excel - 存在某些条件时如何隐藏工作表
- javascript - ReferenceError:在初始化之前无法访问“$zoho”——reactjs 组件
- c++ - 共享指针混淆
- amazon-web-services - 如何在 alb-ingress-controller AWS 启动的 ALB 上使用 AWS 控制台添加 SSL 证书?
- excel - 过滤后计算行数的最佳方法?
- python - 在 Google Colab 上安装 NVIDIA Rapids 的问题
- android - 移动设备底部的空白,无法在 Chrome 模拟器中重现
- excel - 绕过/忽略损坏的 Excel 文件