Scala Design Patterns.
上QQ阅读APP看书,第一时间看更新

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 clear and the value of notificationMessage have to be handled by the classes that will mix with the Notifier interface. Moreover, the traits can require a class to have a specific variable inside it. This is somewhat similar to abstract classes in other languages.