Scala 多繼承 & 依賴注入

破棉襖發表於2016-12-13
依賴注入:

trait Config {
  load
  val text: String
  def load: Unit
}

trait InMemoryConfig extends Config {
  lazy val text = "Hello"
  def load = println("load: " + text)
}

trait Context

trait MyContext extends Context {
  this: Config =>
  def welcome = this.text
}

object Env extends MyContext with InMemoryConfig

println(Env.text)

結果:
load: Hello
Hello

多繼承:
class Person
trait TTeacher extends Person {

  def teach = {println(" TTeacher")}

}
trait TPianoPlayer extends Person {

  def playPiano = {println("I’m playing piano. ")} //實方法,已實現

}
object PianoplayingTeacher extends Person with TTeacher with TPianoPlayer

PianoplayingTeacher.teach
PianoplayingTeacher.playPiano
結果:
 TTeacher
I’m playing piano.





來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29754888/viewspace-2130387/,如需轉載,請註明出處,否則將追究法律責任。

相關文章