Scala Trait

Scala Trait

大多数的时候,Scala中的trait有点类似于Java中的interface。正如同java中的class可以implement多个interface,scala中的calss也可以extend多个trait。因此你看你会看到类似于这样的代码:

 class Woodpecker extends Bird with TreeScaling with Pecking

scala的trait具有比java中的interface强大的多的功能,正如同java中的abstract class可以具有一些方法实现一样,scala中的trait也可以拥有implemented methods。但是和java中的abstract class不相同的是,你可以将多个trait糅合到一个class中,也可以控制哪些class可以将trait糅合进去。

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

如果方法不需要任何的参数的话,那么就可以使用def只declare方法的名字,而不需要()。当然如果方法需要参数的话,那么和平时一样,加上括号:

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

当一个类继承一个trait的时候,使用的是extend关键字,如果需要集成多个trait的时候,那么需要使用extendwith关键字,也就是第一个trait使用extend,后续的都是用with。如下面的例子:

class Mp3SoundPlayer extends BaseSoundPlayer {...}

class Foo extends BaseClass with Trait1 with Trait2 { ...}

但是如果一个class已经extend另外一个class了,那么如果还想继承其他的trait的话,都必须使用with:

abstract class Animal {

}

trait WaggingTail {
    def startTail { println("tail started") }
    def stopTail { println("tail stopped") }
}

trait FourLeggedAnimal {
    def walk
    def run
}

class Dog extends Animal with WaggingTail with FourLeggedAnimal {
    // implementation code here ...
    def speak { println("Dog says 'woof'") }
    def walk { println("Dog is walking") }
    def run { println("Dog is running") }
}

如果一个class extends一个trait,如果它并没有全部实现trait中定义的抽象方法,那么这个class就必须标记为abstract。

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

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

另外,trait也可以extend其他的trait

trait Mp3BaseSoundFilePlayer extends BaseSoundPlayer{
    def getBasicPlayer: BasicPlayer
    def getBasicController: BasicController
    def setGain(volume: Double)
}

定义一个trait,然后给他定义一个faild并且给初始化值,就意味着让它concrete,如果不给值的话,就会让他abstract。

trait PizzaTrait {
    var numToppings: Int // abstract
    var size = 14 // concrete
    val maxNumToppings = 10 // concrete
}

然后对于extends这个PizzaTrait的类中,如果没有给abstract field给值的话,那么就必须标记这个类为abstract、

class Pizza extends PizzaTrait {
    var numToppings = 0 // 'override' not needed
    size = 16 // 'var' and 'override' not needed
}

从上面的例子可以看出,在trait中可以使用var或者val来定义faild,然后在subclass或者trait中不必使用override关键字来重写var faild。但是对于val faild需要使用override关键字。

trait PizzaTrait {
    val maxNumToppings: Int
}

class Pizza extends PizzaTrait {
    override val maxNumToppings = 10 // 'override' is required
}

尽管scala中也有abstract class,但是使用trait更加的灵活.

如果我们想限制那些class可以嵌入trait的话,我们可以使用下面的语法:

 trait [TraitName] extends [SuperThing]

这样只有extend了SuperThing类型的trait, class, abstract class才能够嵌入TraitName, 比如:

class StarfleetComponent
trait StarfleetWarpCore extends StarfleetComponent
class Starship extends StarfleetComponent with StarfleetWarpCore

另外一个例子:

abstract class Employee
class CorporateEmployee extends Employee
class StoreEmployee extends Employee

trait DeliversFood extends StoreEmployee
// this is allowed
class DeliveryPerson extends StoreEmployee with DeliversFood
// won't compile
class Receptionist extends CorporateEmployee with DeliversFood

如果我们想使得Trait只能够被继承了特定类型的类型使用的时候,就可以使用下面的样例:

For instance, to make sure a StarfleetWarpCore can only be used in a Starship , mark the StarfleetWarpCore trait like this:

trait StarfleetWarpCore {
    this: Starship =>
    // more code here ...
}

class Starship
class Enterprise extends Starship with StarfleetWarpCore

trait WarpCore {
    this: Starship with WarpCoreEjector with FireExtinguisher =>
}

表名WarpCore 只能被同时继承了Starship 、WarpCoreEjector 、WarpCoreEjector 这三个东西的东西嵌入

class Starship
trait WarpCoreEjector
trait FireExtinguisher
// this works
class Enterprise extends Starship
with WarpCore
with WarpCoreEjector
with FireExtinguisher

如果我们想限制Trait只能被拥有特定方法的类型所嵌入的话,可以参考下面的例子:

trait WarpCore {
    this: { def ejectWarpCore(password: String): Boolean } =>
}

只有定义有ejectWarpCore方法的classes才能嵌入WarpCore

class Starship {
    // code here ...
}

class Enterprise extends Starship with WarpCore {
    def ejectWarpCore(password: String): Boolean = {
        if (password == "password") {
            println("ejecting core")
                true
            } else {
                false
        }
    }
}

当然也可以要求必须有多个方法:

trait WarpCore {
    this: {
    def ejectWarpCore(password: String): Boolean
    def startWarpCore: Unit
    } =>
}

class Starship
class Enterprise extends Starship with WarpCore {
    def ejectWarpCore(password: String): Boolean = {
        if (password == "password") { println("core ejected"); true } else false
    }
    def startWarpCore { println("core started") }
}

我们可以在object instance创建的时候嵌入Traits。

class DavidBanner
    trait Angry {
    println("You won't like me ...")
}

object Test extends App {
    val hulk = new DavidBanner with Angry
}

这个代码将会输出:“You won’t like me ...”

这个技巧对于debug一些东西的时候比较方便:

trait Debugger {
    def log(message: String) {
    // do something with message
    }
}
// no debugger
val child = new Child
// debugger added as the object is created
val problemChild = new ProblemChild with Debugger

如果你想在Scala中implement Java interface,看下面的例子;

假定现在有3个java interface:

// java
public interface Animal {
public void speak();
}
public interface Wagging {
public void wag();
}
public interface Running {
public void run();
}

我们在Scala中就可以使用类似于下面的写法

// scala
class Dog extends Animal with Wagging with Running {
def speak { println("Woof") }
def wag { println("Tail is wagging!") }
def run { println("I'm running!") }
}

参考资料

时间: 2024-08-25 20:57:34

Scala Trait的相关文章

Coursera Scala 4-1:函数作为对象

Coursera Scala 4-1:函数作为对象 Functions Types Relate to Classes Scala是纯粹的面向对象的语言,函数是拥有apply方法的对象. 函数类型A=>B等价于: package scala trait Function1[A,B]{ def apply(x:A):B } Functions Values Ralate to Objects 匿名函数 (x:Int) => x*x 等价于: { class AnonFun extends Fun

Spark:大数据的“电光石火”

Spark已正式申请加入Apache孵化器,从灵机一闪的实验室"电火花"成长为大数据技术平台中异军突起的新锐.本文主要讲述Spark的设计思想.Spark如其名,展现了大数据不常见的"电光石火".具体特点概括为"轻.快.灵和巧". 轻:Spark 0.6核心代码有2万行,Hadoop 1.0为9万行,2.0为22万行.一方面,感谢Scala语言的简洁和丰富表达力:另一方面,Spark很好地利用了Hadoop和Mesos(伯克利 另一个进入孵化器的

Scalaz(27)- Inference & Unapply :类型的推导和匹配

  经过一段时间的摸索,用scala进行函数式编程的过程对我来说就好像是想着法儿如何将函数的款式对齐以及如何正确地匹配类型,真正是一种全新的体验,但好像有点太偏重学术型了. 本来不想花什么功夫在scala的类型系统上,但在阅读scalaz源代码时往往遇到类型层面的编程(type level programming),常常扰乱了理解scalaz代码思路,所以还是要简单的介绍一下scala类型系统的一些情况.scala类型系统在scala语言教材中一般都提及到了.但有些特殊的类型如phantom t

这里我们可以看到:Person是个多层次对象,包含多层嵌入属性对象(multi-layer embeded objects)。如果需要更改Person类型实例中的任何字段时,我们可以直接用行令方式(imperative style):

  scala中的case class是一种特殊的对象:由编译器(compiler)自动生成字段的getter和setter.如下面的例子: 1 case class City(name:String, province: String) 2 case class Address(street: String, zip: String, city: City) 3 case class Person(name: String, age: Int, phone: String, address:

Scalaz(6)- typeclass:Functor-just map

  Functor是范畴学(Category theory)里的概念.不过无须担心,我们在scala FP编程里并不需要先掌握范畴学知识的.在scalaz里,Functor就是一个普通的typeclass,具备map over特性.我的理解中,Functor的主要用途是在FP过程中更新包嵌在容器(高阶类)F[T]中元素T值.典型例子如:List[String], Option[Int]等.我们曾经介绍过FP与OOP的其中一项典型区别在于FP会尽量避免中间变量(temp variables).FP

Scalaz(17)- Monad:泛函状态类型-State Monad

  我们经常提到函数式编程就是F[T].这个F可以被视为一种运算模式.我们是在F运算模式的壳子内对T进行计算.理论上来讲,函数式程序的运行状态也应该是在这个运算模式壳子内的,也是在F[]内更新的.那么我们就应该像函数式运算T值一样,也有一套函数式更新程序状态的方法.之前我们介绍了Writer Monad.Writer也是在F[]内维护Log的,可以说是一种状态维护方式.但Writer的Log是一种Monoid类型,只支持Semigroup的a|+|b操作,所以只能实现一种两段Log相加累积这种效

讨喜的隔离可变性(八)类型化角色和Murmurs

使用了类型化角色的EnergySource使我们能够以调用函数的形式来掩盖后台顺序处理异步消息的过程,在实现了线程安全的同时又可以免去显式同步的困扰.虽然创建类型化角色并不困难,但此时我们的EnergySource却还是一个丢失了关键特性的半成品--即还没有可以周期性自动补充电量的能力. 在上一章我们所实现的版本中,由于整个动作都是在后台完成,所以电量补充的动作是不需要任何用户介入的.只要我们启动了电源,就会有一个专门的timer负责每秒钟为电源增加一格电量. 然而在使用了类型化角色的版本中,实

Scalaz(8)- typeclass:Monoid and Foldable

 Monoid是种最简单的typeclass类型.我们先看看scalaz的Monoid typeclass定义:scalaz/Monoid.scala 1 trait Monoid[F] extends Semigroup[F] { self => 2 //// 3 /** The identity element for `append`. */ 4 def zero: F 5 ... Monoid trait又继承了Semigroup:scalaz/Semigroup.scala 1 tra

Scalaz(7)- typeclass:Applicative-idomatic function application

   Applicative,正如它的名称所示,就是FP模式的函数施用(function application).我们在前面的讨论中不断提到FP模式的操作一般都在管道里进行的,因为FP的变量表达形式是这样的:F[A],即变量A是包嵌在F结构里的.Scalaz的Applicative typeclass提供了各种类型的函数施用(function application)和升格(lifting)方法.与其它scalaz typeclass使用方式一样,我们只需要实现了针对自定义类型的Applica