上QQ阅读APP看书,第一时间看更新
Extending traits
Traits can also extend each other. Have a look at the following example:
trait Ping {
def ping(): Unit = {
System.out.println("ping")
}
}
trait Pong {
def pong(): Unit = {
System.out.println("pong")
}
}
trait PingPong extends Ping with Pong {
def pingPong(): Unit = {
ping()
pong()
}
}
object Runner extends PingPong {
def main(args: Array[String]): Unit = {
pingPong()
}
}
The preceding example is simple and it should really just make the Runner object mix the two traits separately. Extending traits is useful in a design pattern called Stackable Traits, which we will be looking into later in this book.