我尝试感受implicit
Scala 中参数的优势。(已编辑:使用匿名函数时的特殊情况。请查看此问题中的链接)
我尝试根据这篇文章进行简单的仿真。在哪里解释了如何Action
工作PlayFramework
。这也与那个有关。
以下代码就是为此目的:
object ImplicitArguments extends App {
implicit val intValue = 1 // this is exiting value to be passed implicitly to everyone who might use it
def fun(block: Int=>String): String = { // we do not use _implicit_ here !
block(2) // ?? how to avoid passing '2' but make use of that would be passed implicitly ?
}
// here we use _implicit_ keyword to make it know that the value should be passed !
val result = fun{ implicit intValue => { // this is my 'block'
intValue.toString // (which is anonymous function)
}
}
println(result) // prints 2
}
我想打印“1”。
如何避免传递魔法“2”但使用隐含定义的“1”?
另请参阅我们不在定义中使用的情况implicit
,但它存在,因为匿名函数通过implicit
.
编辑:
以防万一,我发布另一个示例 - 简单模拟 Play' 的Action
工作原理:
object ImplicitArguments extends App {
case class Request(msg:String)
implicit val request = Request("my request")
case class Result(msg:String)
case class Action(result:Result)
object Action {
def apply(block:Request => Result):Action = {
val result = block(...) // what should be here ??
new Action(result)
}
}
val action = Action { implicit request =>
Result("Got request [" + request + "]")
}
println(action)
}