Scala 多继承问题

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala 多继承问题相关的知识,希望对你有一定的参考价值。

多继承问题:

 

object LoadIssueDemo extends App {

  import java.io.PrintWriter

  trait Logger {
    def log(msg: String): Unit
  }

  trait FileLogger extends Logger {
    val fileName: String
    val fileOutput = new PrintWriter(fileName: String)
    fileOutput.println("#")

    def log(msg: String): Unit = {
      fileOutput.print(msg)
      fileOutput.flush()
    }
  }

  class Person

  class Student(var name: String) extends Person with FileLogger {
    override val fileName: String = "file.log"

  }

  new Student("Win").log("trait demo")

}

运行结果:

 

原因:fileName还未初始化,就被方法调用。

解决方法:

1. 提前定义 (代码不够优雅)

object PreDefineDemo  extends App{
  import java.io.PrintWriter

  trait Logger{
    def log(msg: String): Unit
  }

  trait FileLogger extends Logger {
    val fileName: String
    val fileOutput = new PrintWriter(fileName: String)
    fileOutput.println("#")

    def log(msg: String): Unit ={
      fileOutput.print(msg)
      fileOutput.flush()
    }
  }

  class Person
  class Student(var name: String) extends Person with FileLogger{
    override val fileName: String = "file.log"

  }

  new { override val fileName: String = "file.log"} with Student("Win").log("trait demo")

}

2. 懒加载(推荐)

object LazyLoadDemo extends App{
  import java.io.PrintWriter

  trait Logger{
    def log(msg: String): Unit
  }

  trait FileLogger extends Logger {
    val fileName: String
    lazy val fileOutput = new PrintWriter(fileName: String)

    def log(msg: String): Unit ={
      fileOutput.print(msg)
      fileOutput.flush()
    }
  }

  class Person
  class Student(var name: String) extends Person with FileLogger{
    override val fileName: String = "file.log"

  }

  val s = new Student("Win")
  s.log("#")
  s.log("Lazy demo")

}

 

以上是关于Scala 多继承问题的主要内容,如果未能解决你的问题,请参考以下文章

快学Scala 第十八课 (trait多继承)

linux打开终端如何启动scala,如何在终端下运行Scala代码片段?

Scala初识

Scala 继承类型不满足父类型要求

详解 Scala 模式匹配

php如何实现多继承?