Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Programming in Scala > Chapter 12: Traits - Pg. 217

Chapter 12 Traits Traits are a fundamental unit of code reuse in Scala. A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits. This chapter shows you how traits work and shows two of the most common ways they are use- ful: widening thin interfaces to rich ones, and defining stackable modifica- tions. It also shows how to use the Ordered trait and compares traits to the multiple inheritance of other languages. 12.1 How traits work A trait definition looks just like a class definition except that it uses the key- word trait . An example is shown in Listing 12.1: trait Philosophical { def philosophize() { println("I consume memory, therefore I am!") } } Listing 12.1 · The definition of trait Philosophical . This trait is named Philosophical . It does not declare a superclass, so like a class, it has the default superclass of AnyRef . It defines one method, named philosophize , which is concrete. It's a simple trait, just enough to show how traits work. 217