ITPub博客

首页 > 应用开发 > > Scala 多继承 & 依赖注入

Scala 多继承 & 依赖注入

作者:u_509a2a8fdb46 时间:2019-08-22 15:55:57 0 删除 编辑
依赖注入:

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博客 ” ,链接:https://blog.itpub.net/69927062/viewspace-3138530/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-08

  • 博文量
    210
  • 访问量
    38