简体   繁体   中英

Overriding implicit setter method with a trait in Scala

I'm trying to implement a stackable trait pattern in Scala (similar to http://www.artima.com/scalazine/articles/stackable_trait_pattern.html ). Here's my attempt. I start defining a simple class:

class Topping(var name:String)

That class declaration should automatically create a getter and a setter method for variable called "name". So then I create a trait extending this class:

trait LoggingNameTrait extends Topping {

  override def name_=(aName:String) {
    print(aName)
    super.name_=(aName) // this line doesn't compile
  }

}

If the code above worked, it should override the implicit setter for the "name" field, printing it on the console and then calling the setter of the class which uses the trait. I get a "super may not be used on variable name".

Do you know why the Scala compiler doesn't let me override the implicit setter?

It's an implementation restriction: super only works for def s.

https://issues.scala-lang.org/browse/SI-1938

设置器的名称不是name_ ,而是name_= (请注意等号)。

I believe that though scala in some sense creates the name_= method automatically when you declare the variable, it is not available for overriding and the like unless you declare it explicitly. The following, however, should work:

class Topping(var _name:String) {
    def name : String = _name
    def name_= (s : String) { _name = s }
}

trait LoggingNameTrait extends Topping {

  abstract override def name_=(aName:String) {
    print(aName)
    super.name_=(aName) // this line doesn't compile   }

}

This should be functionally equivalent to what you were trying initially,

val t = new Topping with LoggingNameTrait
t.name = "Name"

Will print out "Name" and set the internal _name value, such that val s = t.name will assign "Name" to s , as you would expect. The only difference is the more explicit definition of the setter and getter functions.

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