上QQ阅读APP看书,第一时间看更新
Traits as classes
Traits can also be seen from the perspective of classes. In this case, they have to implement all their methods and have only one constructor that does not accept any parameters. Consider the following:
trait Beeper {
def beep(times: Int): Unit = {
1 to times foreach(i => System.out.println(s"Beep number: $i"))
}
}
Now, we can actually instantiate Beeper and call its method. The following is a console application that does just this:
object BeeperRunner {
val TIMES = 10
def main (args: Array[String]): Unit = {
val beeper = new Beeper {}
beeper.beep(TIMES)
}
}
As expected, after running the application, we will see the following output in our Terminal:
Beep number: 1
Beep number: 2
Beep number: 3
Beep number: 4
Beep number: 5
Beep number: 6
Beep number: 7
Beep number: 8
Beep number: 9
Beep number: 10