Traits versus classes

Traits could be similar, but also very different to classes. It could be hard for a developer to choose which one to use in various cases but here we will try to provide some general guidelines that should help.

Use classes:

  • When a behavior is not going to be reused at all or in multiple places
  • When you plan to use your Scala code from another language, for example, if you are building a library that could be used in Java

Use traits:

  • When a behavior is going to be reused in multiple unrelated classes.
  • When you want to define interfaces and want to use them outside Scala, for example Java. The reason is that the traits that do not have any implementations are compiled similar to interfaces.

Get Scala Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.