Chapter 7Traits

Java permits only single implementation inheritance, but that forces a model of linear hierarchy. The real world, however, is full of crosscutting concerns—concepts that cut across and affect abstractions that do not fall under a single class hierarchy. Security, logging, validation, transactions, and resource management are all examples of such crosscutting concerns in a typical enterprise application. Since we’re limited to single class hierarchy, implementing these crosscutting concerns gets quite hard—it often requires duplication of code or use of heavyweight tools. Scala solves the problem using traits.

Traits are like interfaces with a partial implementation. Traits provide a middle ground between single and multiple ...

Get Pragmatic Scala 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.