What are the pros of using traits over abstract classes?

前端 未结 7 1458
-上瘾入骨i
-上瘾入骨i 2021-01-30 10:12

Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?

7条回答
  •  不思量自难忘°
    2021-01-30 10:33

    I am quoting from the website of the book Programming in Scala, First Edition and more specifically the section called "To trait, or not to trait?" from Chapter 12.

    Whenever you implement a reusable collection of behavior, you will have to decide whether you want to use a trait or an abstract class. There is no firm rule, but this section contains a few guidelines to consider.

    If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.

    If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy.

    There is a bit more information in the above link regarding traits and I suggest you read the full section. I hope this helps.

提交回复
热议问题