无法覆盖Scala中的varargs方法?

时间:2019-08-06 04:13:52

标签: scala

给出以下基类及其方法之一:

abstract class ServiceIf(val name: String) {


   def run(args: Any*):  Any = {}

尝试的子类实现为:

class RexecIf extends ServiceIf("Rexec") {

   override def run(execParams: ExecParams, nLoops: Int) = {

但是“ varargs”不起作用:

enter image description here

这是否是预期的行为-也就是说varargs应该/不应该用于基类方法?

更新我最初没有提到:目标是将反射中的方法用于配置文件驱动的工作流程。因此,在某些用例中使用基于类型的方法(如第一个答案)可能是切实可行的,但在我的情况下不可行。

3 个答案:

答案 0 :(得分:4)

必须能够使用原始接受的任何参数调用覆盖的方法,而不仅仅是您提供的两个参数。也就是说,呼叫 ` <section class="section-about"> <div class="scene"> <div class="box"> <div class="heading-secondary-background"> <div class="heading-secondary" data-text="10 Best Cities To Travel, Live And Work Remotely In Southeast Asia: Introduction">10 Best Cities To Travel, Live And Work Remotely In Southeast Asia</div> <div class="gradient-2"></div> </div> <div class="box__face box__face--right">Right</div> <div class="box_face box_face--left">Left</div> <div class="box_face box_face--top">Top</div> <div class="box_face box_face--bottom">Bottom</div> </div> </div> </section>必须有效。

还要考虑:

recexif.run(1, 2, 3)

这同样是错误的,因为“覆盖”未实现基本方法的约定。

如果您希望不同的实现接受abstract class Base { def run(arg: Any) = {} } class Derived extends Base { override def run(arg: Int) = {} } 的不同参数,请考虑引入关联的类型或类型参数。例如:

run

答案 1 :(得分:1)

您不能用更具体的方法覆盖常规方法。覆盖方法必须接受基本方法所接受的所有参数。因此,问题中的代码将永远无法正常工作。

当然,您可以使override方法失败,除非它获得所需的值。这是在这种情况下如何工作的示例:

abstract class ServiceIf(val name: String) {
   def run(args: Any*): Any = {}
}

class RexecIf extends ServiceIf("Rexec") {
  override def run(args: Any*) = {
    val Seq(execParams: ExecParams, nLoops: Int) = args
  }
}

如果MatchError与覆盖方法中的模式不匹配,将以args失败。

答案 2 :(得分:-1)

虽然这不是一个“答案”,但它可能是最接近的解决方法-显式使用df[(df.index.time == datetime.time(07, 0))].head(3) 而不是Seq吗?

varargs

除非出现更明确的答案,否则我将继续上述方法,并且仍将获得应有的应有待遇。

相关问题