perfectus
perfectus

Reputation: 466

Calling Super Method in Scala

I came across this code when writing test cases in 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
  }
}

Here is the link. Please explain how super.around works in this case?

Upvotes: 1

Views: 120

Answers (1)

Jesper
Jesper

Reputation: 206896

The around method in class WithApplication has the following signature:

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

Let's ignore the implicit argument, it's not interesting for this explanation.

It takes a call-by-name parameter (t: ⇒ T), and in the around method of class WithDbData it's called with a block, which is the { ... } that's after super.around. That block is what's passed as the parameter t.

Another simple example to show what you can do with this:

// 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")
}

Upvotes: 2

Related Questions