在scala中的自类型特征中调用超类上的方法

在scala中的自类型特征中调用超类上的方法,scala,scala-2.7,Scala,Scala 2.7,我试图创建一个特性,当它混合进来时,它将用调用原始方法然后处理结果的方法替换方法的默认定义 以下是我想做的: class Foo { def bar() : String = "Foos bar" } trait OtherStuff { self : Foo => def bar() : String = self.bar() + " with OtherStuff" } class Quux extends Foo with OtherStuff 如果这是我想要的方式

我试图创建一个特性,当它混合进来时,它将用调用原始方法然后处理结果的方法替换方法的默认定义

以下是我想做的:

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 qux).bar
现在将返回
Foos-bar和其他内容。不幸的是,它不是这样工作的-我得到的是:

<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
是否可以使用trait重写self类型中的方法?如果不是,将
OtherStuff
更改为
扩展Foo
的特性,而不是将其自身类型更改为
Foo
会对所有存在的代码造成任何不良影响,比如

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

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

您需要
抽象覆盖
,并且没有自我类型

trait OtherStuff extends Foo {                                
  abstract override def bar() = super.bar() + " with OtherStuff"
}
然后,
classquox用其他东西扩展Foo
做您想要的事情


可能会感兴趣。

或者您可以执行如下重载操作

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")
问题是,在使用自类型注释时,OtherStuff中定义的“OtherStuff”是Foo的一部分
这种特性与Foo混合在一起,而不是一种子类型的关系。

如果其他东西在我的逻辑中不是Foo呢?没有extendig-Foo就没有其他解决方案了吗?或者我在这里滥用自键入?@Dupont:为什么类Quux应该用其他东西扩展Foo,而不是仅仅扩展其他东西并从继承中获取Foo?您刚刚定义了一个无限递归函数。@TonyK::不,因为这两个
bar
方法的签名不同
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")