【问题标题】:How to call `apply` on a superclass in Scala?如何在 Scala 的超类上调用`apply`?
【发布时间】:2012-06-19 21:06:07
【问题描述】:

我的类继承自某个基类,并实现apply 方法,其签名与基类完全相同。我想从我的班级中调用 base 的 apply 方法。 当我尝试以下操作时:

class MyClass extends BaseClass {
  def apply(k: String, v: String) = {
    super.apply(k, v)
    ...
  }
  ...
}

我收到value apply is not a member of BaseClass... 编译错误。 如何从子类调用 base 的 apply 方法?

另外,为什么可以在没有 override 关键字的情况下覆盖 apply 方法?

编辑:实际代码:

class OAuthParamsBuilder(helper: OAuthParamsHelper)
extends KeyValueHandler {

  def apply(k: String, v: String): Unit = {
    ...
  }
}

class OAuthInitSupportBuilder
extends OAuthParamsBuilder(StandardOAuthParamsHelper) {

  /*override*/ def apply(k: String, v: String): Unit = {
    super.apply(k, v)
    ...
  }
...
}

编辑:我注意到 KeyValueHandler 是一个特征,这可能是一个问题。

trait KeyValueHandler extends ((String, String) => Unit)

【问题讨论】:

  • 你能添加BaseClass的代码吗?
  • 如果您清理并重新编译所有内容,问题是否仍然存在?

标签: scala inheritance overriding superclass super


【解决方案1】:

您不是在帮助我们帮助您,但我怀疑这是基类上apply 的真正定义:

def apply(kv: (String, String)) = ???

编辑

您粘贴的代码还不够,因为它无法重现问题:

trait OAuthParamsHelper
trait KeyValueHandler
class OAuthParamsBuilder(helper: OAuthParamsHelper) extends KeyValueHandler {
  def apply(k: String, v: String): Unit = ???
}
object StandardOAuthParamsHelper extends OAuthParamsHelper
class OAuthInitSupportBuilder extends OAuthParamsBuilder(StandardOAuthParamsHelper) {
  override def apply(k: String, v: String): Unit = {
    super.apply(k, v)
    ???
  }
}

【讨论】:

  • @lpaul7 我无法用您发布的代码重现问题。
猜你喜欢
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
相关资源
最近更新 更多