gcc gcc - 4 years ago 102
Scala Question

Overriding an abstract method while using the method

I want to do something like this

abstract class Foo {

def bar:String
def modifiedFoo:Foo = new Foo(){
override def bar = super.bar+"\n"
}
}


but this is not legitimate ("method bar in class Foo is accessed from super,
it may not be abstract unless it is overriden by a member declared abstract
and override" which inturn is only legal for Traits).

I could move the method modifiedFoo
into the companion object with signature modifiedFoo(foo:Foo) but this is
less elegant.
How do you handle this problem?

Answer Source

I think you can just use self in the following way:

abstract class Foo {

  self: Foo =>

  def bar: String

  def modifiedFoo: Foo = new Foo() {
    override def bar = self.bar + "\n"
  }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download