简体   繁体   English

我可以使用来自特征的方法覆盖scala类方法吗?

[英]Can I override a scala class method with a method from a trait?

class PasswordCaseClass(val password:String)
trait PasswordTrait { self:PasswordCaseClass =>
    override def password = "blue"
}

val o = new PasswordCaseClass("flowers") with PasswordTrait

Is it possible to override PasswordCaseClass 's password with what is provided in PasswordTrait ? 是否可以使用PasswordCaseClass提供的password覆盖PasswordCaseClassPasswordTrait Right now, I receive this error: 现在,我收到此错误:

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

I would like to be able to have something like this: 我希望能够有这样的东西:

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

You can override a def with a val , but you can't do it the other way around. 您可以使用val覆盖def ,但不能用其他方法替代。 A val implies a guarantee -- that it's value is stable and immutable -- that a def does not. val表示保证-其值是稳定且不变的def不是。

This worked for me (with some modifications): 这对我有用(进行了一些修改):

trait PasswordLike {
 val password: String 
}

class PasswordCaseClass(val password:String) extends PasswordLike

trait PasswordTrait extends PasswordLike {
 override val password: String = "blue"
}

and then: 然后:

scala> val o = new PasswordCaseClass("flowers") with PasswordTrait
o: PasswordCaseClass with PasswordTrait = $anon$1@c2ccac

scala> o.password
res1: String = blue

You are trying to override the value with the method definition. 您正在尝试使用方法定义覆盖该值。 It simply makes no sense - they have different semantics. 根本没有意义-它们具有不同的语义。 Values supposed to be calculated once per object lifecycle (and stored within a final class attribute) and methods can be calculated multiple times. 可以在每个对象生命周期中计算一次(并存储在final类属性中)和方法的值可以多次计算。 So what you are trying to do is to brake the contract of the class in a number of ways. 因此,您尝试做的是通过多种方式来取消班级的契约。

Anyway there is also compiler's fault - the error explanation is totally unclear. 无论如何,还有编译器的错误-错误的解释是完全不清楚的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM