Wait the light to fall

trait

焉知非鱼

大多数情况下, Scala 中的 trait 相当于 Java 中的借口, 或者 Raku 中的 Role。Scala 可以继承多个 trait。

trait 作为接口 #

trait BaseSoundPlayer {
    def play
    def close
    def pause
    def stop
    def resume
}

和 OC 中的接口类似, 如果方法带有参数,则声明时加上参数即可:

trait Dog {
    def speak(whatToSay: String)
    def wagTail(enabled: Boolean)
}

类继承 trait 时需要使用 extends 和 with 关键字, 如果类只继承一个 trait, 则只使用 extends 就够了:

class Mp3SoundPlayer extends BaseSoundPlayer { ...

继承一个类和一个或多个 trait 时,对类使用 extends, 对 trait 使用 with:

class Foo extends BaseClass with Trait1 with Traits { ...

当一个类继承多个 trait 时,使用 extends 继承第一个 trait ,对其余的 trait 使用 with:

class Foo extends Trait1 with Trait2 with Trait3 with Trait4 { ...

真是够了, 继承了 trait , 语法还啰嗦还不一致,Raku 就直接 :

class Dog is Animal does eat does jump { ...  

Scala 丑哭。

继承了 trait, 就要实现 trait 中定义好的所有方法:

class Mp3SoundPlayer extends BaseSoundPlayer {
    def play         { // code here ... }
    def close       { // code here ... }
    def pause     { // code here ... }
    def stop        { // code here ... }
    def resume   { // code here ... }
}

如果类继承了 trait 但是没有实现它的抽象方法, 那么这个类就必须被声明为抽象类:

// must be declared abstract because it does not implement all of the BaseSoundPlayer methods
abstract class SimpleSoundPlayer extends BaseSoundPlayer {
    def play   { ... }
    def close { ... }
}

trait 还可以继承另外一个 trait:(😄)

trait Mp3BaseSoundPlayer extends BaseSoundFilePlayer {
    def getBasicPlayer: BasicPlayer
    def getBasicController: BasicController
    def setGain(volume: Double)
}