Black monkey house: Scala trait construction order

There is also a character builder, content constructor by the "Initial field" and other statements constitute
the initial instantiation, left to right, right to left to call

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)
}

Summary of steps
(1) to call the constructor superclass of the current class
(2) a first character trait parent constructor
(3) a first constructor trait
parent character builders (4) The second constructor because they have the characteristics of execution is completed, therefore no longer execute
(5) the characteristics of the second constructor
(6) the current class constructor

Classes and qualities are two concepts here to separate the region
A the extends C
B C the extends
new new A ()
new new B ()

Reproduced in: https: //www.jianshu.com/p/ddee7ebd5a4d

Guess you like

Origin blog.csdn.net/weixin_33895695/article/details/91182508