我无法弄清楚为什么在encryptKey
调用类构造函数时以下代码中的字段未初始化为 3:
trait Logger{
println("Construction of Logger")
def log(msg: String) { println(msg) }
}
trait EncryptingLogger extends Logger {
println("Construction of EncryptingLogger")
val encryptKey = 3
override def log(msg: String){
super.log(msg.map(encrypt(_, encryptKey)))
}
def encrypt(c: Char, key: Int) =
if (c isLower) (((c - 'a') + key) % 26 + 'a').toChar
else if (c isUpper) (((c.toInt - 'A') + key) % 26 + 'A').toChar
else c
}
class SecretAgent (val id: String, val name: String) extends Logger {
println("Construction of SecretAgent")
log("Agent " + name + " with id " + id + " was created.")
}
val bond = new SecretAgent("007", "James Bond") with EncryptingLogger
在我的理解中,创建的对象的线性化将是:
SecretAgent -> EncryptingLogger -> Logger -> ScalaObject
并且构造顺序从右到左,这意味着变量应该在 SecretAgent 的构造函数开始之前已经初始化。但prinln告诉我不同:
scala> val bond = new SecretAgent("007", "James Bond") with EncryptingLogger
Construction of Logger
Construction of SecretAgent
Agent James Bond with id 007 was created.
Construction of EncryptingLogger
bond: SecretAgent with EncryptingLogger = $anon$1@49df83b5
我试图以不同的方式混合相同的特征:
class SecretAgent (val id: String, val name: String) extends Logger with EncryptingLogger
并且变量被及时初始化:
scala> val bond = new SecretAgent("007", "James Bond")
Construction of Logger
Construction of EncryptingLogger
Construction of SecretAgent
Djhqw Mdphv Erqg zlwk lg 007 zdv fuhdwhg.
bond: SecretAgent = SecretAgent@1aa484ca
那么在类定义中混合和在对象中混合有什么区别,有人可以解释一下吗?