Black monkey house: Scala superposition characteristics

super does not mean inheritance, but to loading sequence, right to left, not necessarily call the parent class, but call the mixed nature of the left, not the left, only to call the parent class

More inherited trait of the same parent class, from right to left in turn calls the method of characteristics. Super refers to the qualities inherited traits left from the source is unable to determine where super.method will execute the method, if you want to call the method specified qualities, you can specify:. Super [ConsoleLogger] .log (...) where generic It must be the characteristics of the type of direct superclass

trait Logger4 {
  def log(msg: String);
}

trait ConsoleLogger4 extends Logger4 {
  def log(msg: String) {
    println(msg)
  }
}

trait TimestampLogger4 extends ConsoleLogger4 {
  override def log(msg: String) {
    super.log(new java.util.Date() + " " + msg)
  }
}

trait ShortLogger4 extends ConsoleLogger4 {
  override def log(msg: String) {
    super.log(if (msg.length <= 15) msg else s"${msg.substring(0, 12)}...aaaa")
  }
}

class Account4 {
  protected var balance = 0.0
}

abstract class SavingsAccount4 extends Account4 with Logger4 {
  def withdraw(amount: Double) {
    if (amount > balance) log("余额不足")
    else balance -= amount
  }
}

object Main4 extends App {
  //super  特质 从右到左   ShortLogger4  ->  TimestampLogger4
  val acct1 = new SavingsAccount4 with TimestampLogger4 with ShortLogger4
  //TimestampLogger4 -> ShortLogger4
  val acct2 = new SavingsAccount4 with ShortLogger4 with TimestampLogger4
  acct1.withdraw(100)
  acct2.withdraw(100)
}

尖叫提示:抽象类混入特质,从右往左调用,super调用的是当前特质左边的特质,如果没有特质了,才调用父类的,而不是直接调用父类的方法,如果想直接调用父类的,可以加泛型限制

Reproduced in: https: //www.jianshu.com/p/807c2811a645

Guess you like

Origin blog.csdn.net/weixin_34004576/article/details/91182502