我正在玩有关Scala in Action book http://www.manning.com/raychaudhuri/的代码示例
引自https://github.com/nraychaudhuri/scalainaction/blob/master/chap01/LoopTill.scala
// Run with >scala LoopTill.scala or
// run with the REPL in chap01/ via
// scala> :load LoopTill.scala
object LoopTillExample extends App {
def loopTill(cond: => Boolean)(body: => Unit): Unit = {
if (cond) {
body
loopTill(cond)(body)
}
}
var i = 10
loopTill (i > 0) {
println(i)
i -= 1
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码cond: => Boolean是我困惑的地方.当我改变cond:() => Boolean它失败了.
有人可以解释一下我之间有什么不同
cond: => Boolean
Run Code Online (Sandbox Code Playgroud)
和
cond:() => Boolean
Run Code Online (Sandbox Code Playgroud)
它们不是都代表功能的参数吗?
假设我们有Object作为apply方法的参数:
object Wrapper {
def apply(block: TypeA => String) = {
TypeA a = ...
block(a)
}
}
Run Code Online (Sandbox Code Playgroud)
TypeA 是域类型的应用程序.
现在,当我定义内联块时,我可以将TypeA参数定义为隐式:
Wrapper { implicit a => functionThatUseImplicitA() }
Run Code Online (Sandbox Code Playgroud)
但是如果block参数不是Function1,但是Function2呢?如何将两个参数定义为隐式?
object Wrapper2 {
def apply(block: (TypeA, TypeB) => String) = {
TypeA a = ...
TypeB b = ...
block(a, b)
}
}
Run Code Online (Sandbox Code Playgroud)
这个不起作用:
Wrapper { implicit (a, b) => functionThatUseImplicitAB() }
Run Code Online (Sandbox Code Playgroud)
唯一的解决方法是将它们定义为val:
Wrapper { (a, b) =>
implicit val ia …Run Code Online (Sandbox Code Playgroud) scala ×2