Decorating with Traits

You can use traits to decorate objects with capabilities—see the Decorator pattern in Gamma et al.’s Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95]. This pattern can help keep the inheritance hierarchy relatively flat while providing reasonable extensibility. We’ll explore this pattern, and how traits play a vital role, with an example.

Suppose we want to run different checks on an applicant—credit, criminal records, employment, and so on. We’re not interested in all the checks all the time. An applicant for an apartment may need to be checked for credit history and a criminal record. On the other hand, an applicant for employment may need to be checked for a criminal record and previous employment. ...

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.