需要在函数顶部调用其他方法

Require other method to be called at top of function

我正在寻找一种方法来验证某个方法是否在函数的其余部分之前被调用。

比如superclass中有一个setup函数Super,我想保证每个subclass调用super.setup()在 subclass 做任何其他事情之前,确保在使用其他方法之前一切都已经设置好。

我能得到的最好的是这个,这不是很容易或不惯用

class CalledSuper

class Super {
  def setup() = {
    println("Doing some necessary things")
    new CalledSuper
  }

  def printText(s: String)(implicit ev: CalledSuper) = println(s)
}

class Foo extends Super {
  override def setup() = {
    //printText("In subclass's method") error: Could not find implicit value
    implicit val proof = super.setup()
    printText("In subclass's method")
    proof
  }

  def fooBar() = {
    printText("I don't need to call super.setup")(new CalledSuper)
  }
}

虽然这不是很好

  1. 它迫使我将 setup 的结果分配给 implicit val
  2. 它将我重写的 setup 方法强制为 return 一个 CalledSuper 对象。
  3. 它迫使我让 Super class 中的所有方法都接受一个 CalledSuper 对象。
  4. 它只适用于 Super class 中的方法。 subclass的setup函数在调用setup之前仍然可以使用其他方法。不过,这并不是什么大问题。

我的主要问题是#3。这很不方便,因为如果我有一些其他方法 fooBar 也需要使用 printText 方法(当前采用隐式参数)但不需要调用 super.fooBar,那么它只是烦人,因为我不得不不必要地创建一个 CalledSuper 对象,即使在不需要的时候也是如此。

我想知道是否有更好的方法要求在其他方法之前调用一个方法(不仅是为了调用 super.foo 而是要求调用任何方法),因为我不能查找有关 Scala 的任何问题。我可以接受 "hacks" 和粗略的解决方法,只要它们不涉及构建整个编译器插件(或任何其他类似规模的插件)即可。

编辑:澄清一下,super.setup() 的例子只是一个例子。可能还有一些其他方法,如 baz,不必调用 super.baz() 但需要调用 validate() 或类似的方法。

我建议您以不同的方式设计您的首要策略:

class Super {
  def superSetup() = {
    println("Doing some necessary things")
  }

  final def setup() = {
    superSetup()
    setupCustomize()
  }

  def setupCustomize() = {
  }

}


class Foo extends Super {
  override def setupCustomize() = {
    printText("In subclass's method")
  }
}

如果您不希望 superSetup 的顺序可变,请将其作为实现的一部分,即 final