scala中的模式匹配。参数表现出多态或者是子类时的行为是什么::

时间:2018-06-04 15:13:02

标签: java scala inheritance polymorphism pattern-matching

我是scala的新手我在java方面有一些经验。在他们网站的模式匹配部分,他们提到当参数传递给函数时,可以根据参数的引用类型实现不同的逻辑。如果是这样,当扩展许多类和接口的参数传递给包含它实现的所有类和接口的模式匹配时,行为会是什么? 如果只实现了第一个类/接口,那么可以解决它实现的所有类/接口相关的所有逻辑?

Code from scala website

Link to website

1 个答案:

答案 0 :(得分:1)

You are correct that a match statement will execute only the first case that matches, it will not check or execute later matches (otherwise case _ would always be executed).

There is no "work-around" because this isn't a bug or a limitation, it is a very useful feature of the language.


It sounds as if you have a number of different traits each of which has different behaviour and you want to execute the behaviour for all the traits.

The best way to do this is to write separate functions to match against each trait (Sum Var etc.) and call them one by one on the Tree instance. You can make a sequence of these and use foldLeft to apply each of them in turn. Since your derive function returns a new Tree instance you need to be clear about which order you want to apply the operations.

It remains unclear to me why you have a single object that represents both a Var and a Const, so I suspect that there is a deeper problem with your data structures.