简体   繁体   中英

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 ? 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. A val implies a guarantee -- that it's value is stable and immutable -- that a def does not.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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