Composing with self-types

In the previous subsection, we saw how we were forced to extend Connector in our Watch class in order to properly compile our code. There are cases where we might actually want to enforce a trait to be mixed into a class that also has another trait or multiple traits mixed into it. Let's imagine that we want to have an alarm that must be able to notify us, no matter what:

trait AlarmNotifier {  this: Notifier =>    def trigger(): String}

In the preceding code, we've shown a self-type. The highlighted piece of code brings all the methods of Notifier to the scope of our new trait and it also requires that any class that mixes in AlarmNotifier should also mix in Notifier. Otherwise, a compilation error will occur. Instead ...

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.