Why avoid subtyping?

前端 未结 8 971
长发绾君心
长发绾君心 2020-12-02 07:55

I have seen many people in the Scala community advise on avoiding subtyping \"like a plague\". What are the various reasons against the use of subtyping? What are the altern

8条回答
  •  广开言路
    2020-12-02 08:28

    My answer does not answer why it is avoided but tries to give another hint at why it can be avoided.

    Using "type classes" you can add an abstraction over existing types/classes without modifying them. Inheritance is used to express that some classes are specializations of a more abstract class. But with type classes you can take any existing classes and express that they all share a common property, for example they are Comparable. And as long as you are not concerned with them being Comparable you don't even notice it. The classes don't inherit any methods from some abstract Comparable type as long as you don't use them. It's a bit like programming in dynamic languages.

    Further reads:

    http://blog.tmorris.net/the-power-of-type-classes-with-scala-implicit-defs/

    http://debasishg.blogspot.com/2010/07/refactoring-into-scala-type-classes.html

提交回复
热议问题