Traits as interfaces

Traits can be viewed as interfaces in other languages, for example, Java. However they, allow the developers to implement some or all of their methods. Whenever there is some code in a trait, the trait is called a mixin. Let's have a look at the following example:

trait Alarm {  def trigger(): String}

Here, Alarm is an interface. Its only method, trigger, does not have any implementation and if mixed in a non-abstract class, an implementation of the method will be required.

Let's see another trait example:

trait Notifier {  val notificationMessage: String  def printNotification(): Unit = {    System.out.println(notificationMessage)  }  def clear()}

The Notifier interface shown previously has one of its methods implemented, and ...

Get Scala Design Patterns - 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.