24

我正在尝试创建一个特征,当混合时,它将用调用原始方法然后操作结果的方法替换方法的默认定义。

这是我正在尝试做的事情:

class Foo {
  def bar() : String = "Foos bar"
}

trait OtherStuff {
  self : Foo =>
  def bar() : String = self.bar() + " with OtherStuff"
}

class Quux extends Foo with OtherStuff

如果这按我想要的方式工作,那么(new Quux).bar现在将返回Foos bar with OtherStuff. 不幸的是,它不是那样工作的——我得到的是:

<console>:6: error: error overriding method bar in class Foo of type ()String;
 method bar in trait OtherStuff of type ()String needs `override' modifier
       class Quux extends Foo with OtherStuff

但是如果我override在定义时使用OtherStuff,我会得到:

<console>:7: error: method bar overrides nothing
         override def bar() : String = self.bar() + " with OtherStuff"

是否可以使用 trait 覆盖自类型中的方法?如果不是,将更OtherStuff改为一种特征,extends Foo而不是具有自我类型的特征,Foo对所有存在的代码做任何不好的事情,比如

class WhatEver extends Foo with Xyz with Pqr with OtherStuff with Abc

我在 scala 2.7.7 中工作,因为这是一个 sbt 构建规则,我们还没有将我们的 sbt 项目升级到 0.10.x 版本。(我们依赖的插件还没有准备好)

4

2 回答 2

34

你需要abstract override并且不需要自我类型。

trait OtherStuff extends Foo {                                
  abstract override def bar() = super.bar() + " with OtherStuff"
}

然后class Quux extends Foo with OtherStuff做你想做的。

这篇文章可能很有趣。

于 2011-07-27T19:02:28.583 回答
1

或者您可以进行如下重载

class Foo {
  def bar() : String = "Foos bar"}
trait OtherStuff {
  self : Foo =>
  def bar( s : String) : String = self.bar() + s}

class Quux extends Foo with OtherStuff
(new Quux).bar(" with other stuff")

问题是,使用 self 类型注释,当 Trait 与 Foo 混合时,OtherStuff 中定义的“其他东西”是 Foo 的一部分,而不是子类型关系。

于 2014-03-04T11:04:30.017 回答