Black monkey house: Scala traits in specific fields

You can define specific characteristics in the field, if initialized it is a specific field, if you do not initialize the abstract field.
The mixed nature of the class will have the field, the field is not inherited, but simply added to the class, their own field, just like a little copy

trait Logger7 {
  def log(msg: String)
  //抽象字段
  val x:Int
  //非抽象字段
  val y:Int = 10
}

trait ConsoleLogger7 extends Logger7 {
  def log(msg: String) {
    println(msg)
  }
}

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

class Account7 {
  protected var balance = 0.0
}

class SavingsAccount7 extends Account7 with ConsoleLogger7 with ShortLogger7 {
  var interest = 0.0
  def withdraw(amount: Double) {
    if (amount > balance) log("余额不足")
    else balance -= amount
  }
}

object Main7 extends App {
  val acct = new SavingsAccount7
  acct.withdraw(100)
  println(acct.maxLength)
}

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

Guess you like

Origin blog.csdn.net/weixin_34019144/article/details/91182504