码迷,mamicode.com
首页 > 其他好文 > 详细

Scala 多继承问题

时间:2017-12-10 13:02:44      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:pre   xtend   port   text   java   extend   定义   write   import   

多继承问题:

 

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 多继承问题

标签:pre   xtend   port   text   java   extend   定义   write   import   

原文地址:http://www.cnblogs.com/AK47Sonic/p/8016449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!