【发布时间】:2013-09-17 16:14:48
【问题描述】:
我尝试感受 Scala 中implicit 参数的优势。 (已编辑:使用匿名函数时的特殊情况。请查看此问题中的链接)
我尝试根据this 帖子进行简单的模拟。在哪里解释了Action 在PlayFramework 中的工作原理。这也与that有关。
以下代码就是为此目的:
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”?
另请参阅case,我们在定义中不使用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)
}
【问题讨论】:
-
block(2)总是将 2 作为block的参数。可能你不明白隐式参数的定义,不仅仅是如何“感受优势”。 -
从scala tutorial on implicit parameters 的第一行开始“带有隐式参数的方法可以像普通方法一样应用于参数。在这种情况下,隐式标签无效。但是,如果这样的方法缺少其隐式参数的参数,将自动提供此类参数”。如果一个隐式参数可以覆盖你显式传递的东西的行为,那将是各种混乱
-
我知道我在传递什么,我不奇怪为什么它会打印“2”(阅读时请耐心等待)。有几种情况是如何使用隐式的。请阅读我提供的这两个链接。 @Starge B. 请不要太个人化。我很敏感:)。
-
关于编辑部分:您的
implicit request仅将request放入本地隐式范围 - 这意味着您现在可以调用接受隐式请求的函数,编译器会将其插入。至于Action.applybody... 在这里你用实际请求调用块....做实际的 IO -
说,如果在 apply() 中的 block(...) 中我会隐式使用 [Request],那么我是否使用“隐式请求”都没有关系 - 它将使用请求在某处隐含定义。即使我将自己的请求传递给 Action { myOwnRequest =Result }。困惑我。我想我只需要使用柯里化将我的请求作为第二个参数传递给 apply(...)(implicit request:Request)
标签: scala