初始化trait的抽象字段:
trait Logged { println("Logged constructor") def log(msg: String){ println("Logged")} } trait FileLogger extends Logged { var filename: String override def log(msg: String) { println("filename:" + filename) } }
在trait中定义了抽象字段我们应该如何初始化他呢?
如果我们简单的在类中覆盖,由于trait构造在类构造之前运行,所以无法初始化filename。那怎么办呢?
方法有三种:
前两种属于预先定义
class SavingFile extends { var filename = "hello"} with FileLogger{ }
new SavingFile().log("") (new {var filename = "hello"} with Account() with FileLogger).log("")
运行结果:
Logged constructor
FileLogger constructor
SavingFile constructor
filename:hello
Account constructor
Logged constructor
FileLogger constructor
filename:hello
第三种:因为动态继承trait,是在类构造之后进行,所以可以如下操作:
class AccountTest { println("AccountTest constructor") var filename = "hello" } (new AccountTest() with FileLogger).log("")
运行结果:
AccountTest constructor
Logged constructor
FileLogger constructor
filename:hello