scala中的之前定义
scala中的预先定义Early de?nitions are particularly useful for traits, which do not have normal cons
scala中的预先定义
Early de?nitions are particularly useful for traits, which do not have normal constructor parameters. Example:
预先定义对traits特别有用(traits没有常规构造函数函数),例如:
trait Greeting { val name: String val msg = "How are you, "+name}class C extends { val name = "Bob"} with Greeting { println(msg)}
In the code above, the ?eld name is initialized before the constructor of Greeting is called. Therefore, ?eld msg in class Greeting is properly initialized to "How are you, Bob".
name会在Greeting构造函数调用之前初始化,最终,msg会被正确的初始化为“How are you,Bob”
If name had been initialized instead in C’s normal class body, it would be initialized after the constructor of Greeting. In that case, msg would be initialized to "How are you, <null>".
如果name在常规的C的正常class体内初始化,那么它会在Greeting构造函数中初始化,msg将会初始化为“How are you,<null>”