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

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 assignment in the class body. The reason for this behavior is simple: if we explicitly use val (or var), the compiler will create a field with a getter with the same scope as the parameter. If we just have the parameter, a field and internal getter will be created only if the parameter is used outside the constructor scope, for example, in a method. For completeness, case classes automatically have the val keyword prepended to parameters. After what we said it means that when using val, we actually have a field with the given name and the right scope, and it will automatically override whatever the trait requires us to do.