标签: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") }
标签:pre xtend port text java extend 定义 write import
原文地址:http://www.cnblogs.com/AK47Sonic/p/8016449.html