Scala中的模式匹配如何克服切换案例导致的重复? [英] How does Pattern Matching in Scala overcome duplication that switch case causes?

查看:89
本文介绍了Scala中的模式匹配如何克服切换案例导致的重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我是出于好奇而不是语言功能的重要性。



看起来很棒从命令式编程世界中引入的功能。
我是Scala的新手,仍在尝试弄清楚所有内容,将其庞大的构造集合放入并可以利用。



模式匹配绝对可以比开关盒要好100倍。
,但自从OOP出现以来,我们还是更倾向于使用多态性。



所以我是发现很难理解的是,如果switch case鼓励重复并且我们最好将case相关的代码编写到各个类中,那么Scala的模式匹配如何克服这个问题?



我们仍然可以为各种情况提供类或泛型类,并再次利用多态性满足我们的需求。

解决方案

这是对象和数据结构之间差异的问题。



如果要处理对象,请使用子类型多态性-添加新类型不需要重新编译,重新测试或重新部署



如果要处理数据结构,则可以添加现有算法中的一个,而添加新算法(接口上的方法,位于层次结构的顶部)可以。使用模式匹配-添加新算法不需要rec

阅读有关它的更多信息此处


NOTE: I am asking this question out of inquisitiveness and not questioning the importance of a language feature.

Looks to be a great feature introduced to people from imperative world of programming. I am new to Scala and still trying to figure out where all, do its massive sets of constructs fit in and can be leveraged.

Pattern matching can definitely do stuff 100 x better than the switch case. but still, it is a case construct over which we use to prefer polymorphism since the time OOP came out.

So in short what I am finding difficult to understand is, If switch case encourages duplication and we better write case related code into respective classes then How does Scala's pattern matching overcome this ?

We can still have classes or generic classes for various cases and again leverage polymorphism to our need.

解决方案

It's the matter of the difference between objects and data structures.

If you are dealing with objects use the subtype polymorphism - adding new types doesn't require recompilation, retesting or redeployment of the existing ones, whereas adding a new algorithm (a method on the interface, which is at the top of the hierarchy) does.

If you are dealing with data structures use patter matching - adding new algorithms doesn't require recompilation, retesting or redeployment of the existing ones, whereas adding a new type does.

Read more about it here.

这篇关于Scala中的模式匹配如何克服切换案例导致的重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆