scala:特征中的抽象方法

时间:2014-10-14 17:49:52

标签: scala scala-2.10 traits

我用一个抽象方法创建特征。然后我创建一个使用此特征的类。该类包含具体的重写方法。所以这段代码工作得很好

  trait Logged {
    def log(msg: String)
  }

  class A extends Logged{
    def log(msg: String) {
      println(msg)
    }
    def a(msg: String) {
      log(msg)
    }
  }

  val a = new A
  a.log("jopa")

但是当我创建一个特质链时,事情会变得混乱:

  trait Logged {
    def log(msg: String)
  }

  trait TimestampLogger extends Logged {
    abstract override def log(msg: String) {
      super.log("huy: " + msg)
    }
  }

  class A extends Logged with TimestampLogger {
    def log(msg: String) {
      println(msg)
    }
    def a(msg: String) {
      log(msg)
    }
  }

  val a = new A
  a.log("jopa")

此代码既不适用于overridden log方法修饰符,也不适用于我尝试过的任何内容。 有什么问题?

1 个答案:

答案 0 :(得分:1)

以这种方式使用可堆叠特征:

http://www.artima.com/pins1ed/traits.html#12.5

具体实现必须以线性化顺序在父级中。

new A with TimestampLogger

即,

trait Logged {
    def log(msg: String)
}

trait TimestampLogger extends Logged {
    abstract override def log(msg: String) {
        super.log("huy: " + msg)
    }
}

class A extends Logged {
    def log(msg: String) {
        println(msg)
    }
    def a(msg: String) {
        log(msg)
    }
}

object Test extends App {
    val a = new A with TimestampLogger
    a.log("jopa")
}

或类似。