Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 715
jedesah Avatar asked Oct 08 '13 00:10

jedesah


People also ask

Can override method call super?

A subclass can override methods of its superclass, substituting its own implementation of the method for the superclass's implementation.

Can we override traits?

The trait function can be overridden simply by defining a function with the same name in the class.

Can you call an overridden method?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).

Can we override trait method in PHP?

Traits are a useful way of keeping our code DRY (i.e. not repeating ourselves) and sharing methods amongst classes. The fact that we can override and extend the methods from a trait makes them extremely useful!


1 Answers

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.

like image 130
jedesah Avatar answered Nov 01 '22 08:11

jedesah