在Scala中调用超级方法
我在specs2中编写测试用例时遇到了这段代码在Scala中调用超级方法,scala,specs2,Scala,Specs2,我在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 { "
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
}
}
这是你的电话号码。
请解释
super.around
在这种情况下是如何工作的?类WithApplication
中的around
方法具有以下签名:
def around[T](t: ⇒ T)(implicit arg0: AsResult[T]): Result
让我们忽略隐式的论点,这个解释不有趣
它需要一个(t:⇒ T)
,在类的abround
方法中,使用dbdata
调用它,它是在super.abround
之后的{…}
块。该块作为参数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")
}
//只需在方法中使用名称“block”即可调用块
//(这就是“点名”的意思)
def repeat(n:Int)(block:=>Unit)=for(谢谢你的回答。我是Scala新手,示例和文档非常少,我已经介绍了大部分文档和示例,但我仍然很困惑。你能给我推荐一些书吗?一本新版的已经出版了(我在很多年前从第一版开始学习Scala)。