20

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

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

但现在我想调用函数的先前或超级实现,如下所示:

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

或者

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

但是,这些替代方案都不能编译。知道如何实现吗?

4

3 回答 3

19

这是我一直在寻找的答案。感谢 Shadowlands 用 Scala 的abstract override特性为我指明了正确的方向。

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

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

于 2013-10-08T02:32:13.427 回答
12

我不知道您是否可以进行以下更改,但是可以通过引入额外的 trait(我称之为Repr)并abstract overrideAbstracttrait 中使用来实现您想要的效果:

trait Repr {
    def userRepr: String
}

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

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

trait Abstract extends Repr { self: Result =>
    abstract override def userRepr = "abstract-" + super.userRepr // 'super.' works now
}

您的示例用法现在给出:

scala> val a = new ValDefResult("asd") with Abstract
a: ValDefResult with Abstract = ValDefResult(asd)

scala> a.userRepr
res3: String = abstract-asd
于 2013-10-08T01:02:41.480 回答
10

abstract override是机制,也就是可堆叠的特征。值得补充的是,线性化很重要,因为这决定了super意味着什么。

这个问题是关于自我类型与扩展的规范问答的一个很好的补充。

继承与自我类型不明确的地方:

scala> trait Bar { def f: String = "bar" }
defined trait Bar

scala> trait Foo { _: Bar => override def f = "foo" }
defined trait Foo

scala> new Foo with Bar { }
<console>:44: error: <$anon: Foo with Bar> inherits conflicting members:
  method f in trait Foo of type => String  and
  method f in trait Bar of type => String
(Note: this can be resolved by declaring an override in <$anon: Foo with Bar>.)
              new Foo with Bar { }
                  ^

那么显然,您可以选择:

scala> new Foo with Bar { override def f = super.f }
res5: Foo with Bar = $anon$1@57a68215

scala> .f
res6: String = bar

scala> new Foo with Bar { override def f = super[Foo].f }
res7: Foo with Bar = $anon$1@17c40621

scala> .f
res8: String = foo

或者

scala> new Bar with Foo {}
res9: Bar with Foo = $anon$1@374d9299

scala> .f
res10: String = foo
于 2013-10-08T10:00:58.377 回答