通过特征覆盖方法时如何调用超级方法 [英] How to call super method when overriding a method through a trait

查看:87
本文介绍了通过特征覆盖方法时如何调用超级方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎可以在具有如下特征的类上更改方法的实现:

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

可在此处获得实时代码: http://www.scalakata.com/52534e2fe4b0b1a1c4daa436

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
}

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

但是,这些选择都不能编译.知道如何实现吗?

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

推荐答案

这是我一直在寻找的答案.谢谢Shadowlands通过Scala的abstract override功能为我指明了正确的方向.

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

可在此处获得实时代码: http://www.scalakata.com/52536cc2e4b0b1a1c4daa4a4

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

对于令人困惑的示例代码很抱歉,我正在编写一个处理Scala AST的库,并且没有足够的灵感来更改名称.

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.

这篇关于通过特征覆盖方法时如何调用超级方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆