1

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?

perfectus
  • 466
  • 4
  • 14

1 Answers1

2

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")
}
Community
  • 1
  • 1
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Thanks for the answer. I am new to Scala and there are very fewer examples and documentations, I have covered most of the documentation and example but I still get confused a lot. Can you recommend me some book? – perfectus Jun 06 '16 at 14:04
  • A new version of [Programming in Scala](http://www.amazon.com/Programming-Scala-Updated-2-12/dp/0981531687/ref=sr_1_1?s=books&ie=UTF8&qid=1465222054&sr=1-1&keywords=scala) is out (I've learned Scala a number of years ago from the first edition). – Jesper Jun 06 '16 at 14:08