在 Scala 中调用超级方法

Calling Super Method in Scala

我在 specs2 中编​​写测试用例时遇到了这段代码。

abstract class WithDbData extends WithApplication {
  override def around[T: AsResult](t: => T): Result = super.around {
    setupData()
    t
  }

  def setupData() {
    // setup data
  }
}

"Computer model" should {

  "be retrieved by id" in new WithDbData {
    // your test code
  }
  "be retrieved by email" in new WithDbData {
    // your test code
  }
}

这里是link。 请解释 super.around 在这种情况下是如何工作的?

class WithApplication 中的 around 方法具有以下签名:

def around[T](t: ⇒ T)(implicit arg0: AsResult[T]): Result

让我们忽略隐含的论点,这个解释并不有趣。

需要一个call-by-name parameter(t: ⇒ T),在class的around方法中WithDbData用一个block调用,就是{ ... }super.around 之后。该块是作为参数传递的内容 t.

另一个简单的例子来说明你可以用它做什么:

// Just using the name 'block' inside the method calls the block
// (that's what 'call-by-name' means)
def repeat(n: Int)(block: => Unit) = for (i <- Range(0, n)) {
  block   // This calls the block
}

// Example usage
repeat(3) {
  println("Hello World")
}