Mixing in traits with variables

As we just pointed out, traits might require a class to have a specific variable. An interesting use case would be when we pass a variable to the constructor of a class. This will cover the trait requirements:

class NotifierImpl(val notificationMessage: String) extends Notifier {  override def clear(): Unit = System.out.println("cleared")}

The only requirement here is for the variable to have the same name and to be preceded by the val keyword in the class definition. If we don't use val in front of the parameter in the preceding code, the compiler would still ask us to implement the trait. In this case, we would have to use a different name for the class parameter and would have an override val notificationMessage ...

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.