Override attribute's methods in scala

509 views Asked by At

In scala it's quite easy to override the default accessors and mutators; this makes me feel much more comfortable with public attributes because it allows me to modify access behavior at a later time without changing my class's signature. Here's how that's done:

class Topic {
  var tags = "default"; 
}

becomes:

class Topic{
  private var _tags = "default"; 
  def tags = {
    _tags
  }
  def tags_ =(s:String){
    _tags = s
  }
}

However, this doesn't address a major reason for creating private fields; it doesn't allow for the modification of a component element's behavior. For example, with a Growable, I may want to do something special if I add a new element or clear my list. One way to approach this is to create a class that implements Growable, for example:

class Topic {
  private var _tags:Growable[String] = new MyMutableList[String]() 
  def tags = {
    _tags
  }
  def tags_=(Growable[String]){
    _tags = m
  }
}
class MyMutableList[T] extends MutableList[T](){
    override def +=(t:T) {
      println("adding: " + t.toString())
      super.+=(t)
    }
    override def clear() {
      println("clearing")
      super.clear()
    }
}

However, this doesn't fix the problem completely because 'tags' can still be set equal to any Growable[String]. This would change the clear() method's behavior to the behavior of whatever type was provided.

Is there anyway to override a method of an attribute in the same way that the attribute's accessor/mutator can be overridden? This doesn't compile, but it expresses what I'm trying to do:

class Topic {
  private var _tags:Growable[String] = new MutableList[String](); 
  def tags = {
    _tags
  }
  def tags_=(m:Growable[String]){
    _tags = m
  }
  def tags_.+=(s:String) {
    println("adding: " + t.toString())
    _tags += s
  }
  def tags_.clear(){
    println("clearing")
    _tags.clear()
  }
}
1

There are 1 answers

1
Peter Neyens On BEST ANSWER

You cannot override the methods of an attribute in a class.

  • You could limit the type of your tags attribute, to make it impossible to set the tags attribute to a different Growable[String}.
  • You could also omit the mutator method and add a addTag(tag: String): Unit and a cleanTags : Unit method.