Search code examples
scalapolymorphismmixinstraits

How to call super method when overriding a method through a trait


It would appear that it is possible to change the implementation of a method on a class with a trait such as follows:

trait Abstract { self: Result =>
    override def userRepr = "abstract"
}

abstract class Result {
    def userRepr: String = "wtv"
}

case class ValDefResult(name: String) extends Result {
    override def userRepr = name
}

val a = new ValDefResult("asd") with Abstract
a.userRepr

Live code is available here: http://www.scalakata.com/52534e2fe4b0b1a1c4daa436

But now I would like to call the previous or super implementation of the function such as follows:

trait Abstract { self: Result =>
    override def userRepr = "abstract" + self.userRepr
}

or

trait Abstract { self: Result =>
    override def userRepr = "abstract" + super.userRepr
}

However, none of these alternatives compile. Any idea how this could be accomplished?


Solution

  • Here is the answer I was looking for. Thank you Shadowlands for pointing me in the right direction with Scala's abstract override feature.

    trait Abstract extends Result {
        abstract override def userRepr = "abstract " + super.userRepr
    }
    
    abstract class Result {
        def userRepr: String = "wtv"
    }
    
    case class ValDefResult(name: String) extends Result {
        override def userRepr = name
    }
    
    val a = new ValDefResult("asd") with Abstract
    a.userRepr
    

    Live code is available here: http://www.scalakata.com/52536cc2e4b0b1a1c4daa4a4

    Sorry for the confusing example code, I am writing a library that deals with the Scala AST and was not inspired enough to change the names.