在 Scala 的自类型特征中调用超类上的方法 [英] Calling a method on the superclass in a self-typed trait in scala

查看:41
本文介绍了在 Scala 的自类型特征中调用超类上的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a trait that, when mixed in, will replace the default definition of a method with one that calls the original method and then manipulates the result.

这是我想要做的:

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.不幸的是,它不能那样工作 - 我得到的是:

If this worked the way I wanted it to, then (new Quux).bar would now return Foos bar with OtherStuff. Unfortunately, it doesn't work that way - what I get is:

<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,我得到:

But if I use override when defining OtherStuff, I get:

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

是否可以使用 trait 覆盖自类型中的方法?如果不是,将 OtherStuff 更改为 extends Foo 的特征,而不是具有 Foo 自我类型的特征,会对所有人造成任何不利影响存在的代码说诸如

Is it possible to override a method in a self-type using trait? If not, will changing OtherStuff to be a trait that extends Foo instead of one that has a self-type of Foo do anything bad to all the code that exists saying things like

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

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

I'm working in scala 2.7.7 because this is an sbt build rule, and we haven't upgraded our sbt project to the 0.10.x versions yet. (Plugins we depend on aren't ready yet)

推荐答案

你需要 abstract override 并且没有自我类型.

You need abstract override and no self type for that.

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

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

Then class Quux extends Foo with OtherStuff does what you want.

这篇文章可能很有趣.

这篇关于在 Scala 的自类型特征中调用超类上的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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