Scala Trait 堆叠特性

以一个简单的例子展示 Scala Trait 线性堆叠的特性:

package net.coderbee.scala

trait BaseTrait {
    def action
}

trait Trait0 extends BaseTrait {
    abstract override def action {
        println("action at Trait0")
        super.action
    }
}

trait Trait1 extends BaseTrait {
    abstract override def action() {
        println("action at trait1")
        super.action // 如果某个Trait不调用父类的方法,则会中断Trait的调用栈,这可用以实现过滤
        println("rollback at action at trait1")
    }
}

trait Trait2 extends BaseTrait {
    abstract override def action() {
        println("action at trait2")
        super.action
    }
}

trait BreakTrait extends BaseTrait {
    abstract override def action {
        println("i am break trait, end here ")
    }
}

class ClassWithTrait extends BaseTrait {
    def action() {
        println("action at ClassWithTrait")
    }
}

object StackTrait {

    def main(args: Array[String]) {
        val tr012 = new ClassWithTrait with Trait2 with Trait1 with Trait0
        tr012.action // 从右往左调用 trait 的抽象实现,最后调用本类的。如果中间某个抽象方法没有调用超类的  super 方法,则不会调用到本类

        println
        val tr02 = new ClassWithTrait with Trait2 with Trait0
        tr02.action

        println
        val trBreak = new ClassWithTrait with Trait2 with BreakTrait with Trait1 with Trait0
        trBreak.action
    }
}

输出结果:

继续阅读