美文网首页
trait in scala

trait in scala

作者: 焉知非鱼 | 来源:发表于2017-10-09 23:38 被阅读33次

大多数情况下, Scala 中的 trait 相当于 Java 中的借口, 或者 Perl 6 中的 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 , 语法还啰嗦还不一致,Perl 6 就直接 :

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)
}

相关文章

  • trait in scala

    大多数情况下, Scala 中的 trait 相当于 Java 中的借口, 或者 Perl 6 中的 Role。S...

  • scala学习 - 特质

    本文来自《Programming in Scala》一书 Scala学习之特质(trait) 1 特质的定义 特质...

  • scala的Trait

    Trait基础 scala 中的Trait和Java中的接口(interface)极其类似 接口是彻底的抽象类,所...

  • Spark Sql 源码剖析(二): TreeNode

    零、前置知识 Scala Product trait 一、CurrentOrigin 使用 object Curr...

  • trait

    在scala中,trait相当于java中的interface关键字,可以用来定义接口,但是trait除了定义接口...

  • Scala的trait

    今天看一下scala的trait,用法不讲,就看一下编译再反编译的源码定义一个trait 使用javac命令编译这...

  • Scala特征(Trait)

    Scala Trait(特征) 相当于 Java 的接口,实际上它比接口还功能强大。与接口不同的是,它还可以定义属...

  • Scala详解——Trait

    学习过Java的同学肯定知道Java中有接口(interface)的概念,它在JAVA编程语言中是一个抽象类型,是...

  • scala(十二) 特质

    特质的定义 Scala语言中,采用特质(trait)来代替接口的概念,也就是说,多个类具有相同的特质(trait)...

  • 【Scala】Scala特质

    PS:本篇主要内容来自 《scala 编程》一书。 一、特质的基本概念 在 Scala 中 Trait 为重用代...

网友评论

      本文标题:trait in scala

      本文链接:https://www.haomeiwen.com/subject/whemyxtx.html