class PasswordCaseClass(val password:String)
trait PasswordTrait { self:PasswordCaseClass =>
override def password = "blue"
}
val o = new PasswordCaseClass("flowers") with PasswordTrait
是否可以用PasswordTrait
提供的內容覆蓋PasswordCaseClass
的password
?現在,我收到此錯誤:我可以用特徵中的方法重寫一個scala類方法嗎?
e.scala:6: error: overriding value password in class PasswordCase
Class of type String;
method password in trait PasswordTrait of type => java.lang.String needs to be a stable,
immutable value
val o = new PasswordCaseClass("flowers") with PasswordTrait
^
one error found
我希望能有這樣的事情:
class User(val password:String) {
}
trait EncryptedPassword { u:User =>
def password = SomeCriptographyLibrary.encrypt(u.password)
}
val u = new User("random_password") with EncryptedPassword
println(u.password) // see the encrypted version here
但是,如果我使用字段或方法,Scala應該不會無動於衷嗎? – Geo 2011-04-25 08:37:06
那麼,關於重寫,我認爲def可以被val重寫,但不是相反。 – 2011-04-25 09:02:58