黑猴子的家:Scala 特质构造顺序

特质也是有构造器的,构造器中的内容由“字段的初始化”和一些其它语句构成
初始实例化,是从左到右,调用是从右到左

trait Logger9 {
  println("我在Logger9特质构造器中,嘿嘿嘿。。。")
  def log(msg: String)
}

trait ConsoleLogger9 extends Logger9 {
  println("我在ConsoleLogger9特质构造器中,嘿嘿嘿。。。")
  def log(msg: String) {
    println(msg)
  }
}

trait ShortLogger9 extends Logger9 {
  val maxLength: Int
  println("我在ShortLogger9特质构造器中,嘿嘿嘿。。。")

  abstract override def log(msg: String) {
    super.log(if (msg.length <= maxLength) msg else s"${msg.substring(0, maxLength - 3)}...")
  }
}

class Account9 {
  println("我在Account9构造器中,嘿嘿嘿。。。")
  protected var balance = 0.0
}

abstract class SavingsAccount9 extends Account9 with ConsoleLogger9 with ShortLogger9{
  println("我再SavingsAccount9构造器中")
  var interest = 0.0
  override val maxLength: Int = 20
  def withdraw(amount: Double) {
    if (amount > balance) log("余额不足")
    else balance -= amount
  }
}

object Main9 extends App {
  val acct = new SavingsAccount9 with ConsoleLogger9 with ShortLogger9
  acct.withdraw(100)
  println(acct.maxLength)
}

步骤总结
(1)调用当前类的超类构造器
(2)第一个特质的父特质构造器
(3)第一个特质构造器
(4)第二个特质构造器的父特质构造器由于已经执行完成,所以不再执行
(5)第二个特质构造器
(6)当前类构造器

类和特质是两个概念,在这里区分开来
A extends C
B extends C
new A()
new B()

转载于:https://www.jianshu.com/p/ddee7ebd5a4d

猜你喜欢

转载自blog.csdn.net/weixin_33895695/article/details/91182508