CHAPTER 7

image

Traits

In this chapter you will learn how to construct reusable parts of a program and deal with the tribulations of multiple inheritance, sidestepping the disadvantages of single inheritance by means of the mixing of compositions made possible by traits.

A trait provides code reusability in Scala by encapsulating method and state and then offering the possibility of mixing them into classes thus allowing code reuse. In this way a class can be mixed in with a myriad of traits unlike inheritance where each class is allowed to inherit from just one superclass. Moreover, other than using the keyword trait a trait definition resembles a ...

Get Beginning Scala, Second Edition 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.