【问题标题】:Calling a method on the superclass in a self-typed trait in scala在scala的自类型特征中调用超类上的方法
【发布时间】:2011-10-14 13:05:00
【问题描述】:

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

这是我想要做的:

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

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

<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 版本。 (我们依赖的插件还没有准备好)

【问题讨论】:

    标签: scala scala-2.7


    【解决方案1】:

    您需要 abstract override 并且不需要 self 类型。

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

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

    This article 可能感兴趣。

    【讨论】:

    • 如果 OtherStuff 在我的逻辑中不是 Foo 怎么办?没有extendig Foo就没有另一种解决方案吗?还是我在这里滥用自我打字?
    • @Dupont:为什么类 Quux 应该用 OtherStuff 扩展 Foo 而不是仅仅扩展 OtherStuff 并从继承中获取 Foo?
    【解决方案2】:

    或者你可以像下面这样重载

    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 类型注释,OtherStuff 中定义的“其他东西”是 Foo 的一部分,当 Trait 与 Foo 混合,而不是子类型关系。

    【讨论】:

    • 你刚刚定义了一个无限递归函数。
    • @TonyK.: 不,因为两个bar 方法的签名不同
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2019-05-11
    • 2013-06-09
    • 2011-05-14
    相关资源
    最近更新 更多