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