我想不通,爲什麼在下面的代碼字段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 = [email protected]
我試圖混入同一性狀不同:
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 = [email protected]
那麼有什麼區別在混合類定義和混合對象之間,可以有人解釋一下嗎?
嗨,你能解釋爲什麼超類在構造子類之前不構造嗎?根據線性化規則,EncryptingLogger應該首先被初始化。 – damluar
我更新了問題 – damluar
更新了我的答案 – drexin