29

我了解 Scala 中的隐式参数和隐式转换,但我今天第一次看到这个:匿名函数中参数前面的隐式关键字:

Action { implicit request =>
  Ok("Got request [" + request + "]")
}

隐含关键字在这里做什么?

网络上是否有更多描述用例的资源?

4

3 回答 3

23

这里有两个不同的特点。

首先,request在方法调用中并不是真正的参数。这是匿名函数的参数。匿名函数本身就是方法调用的参数。

其次,在匿名函数中声明隐式参数可以方便地使您免于“强制”将 val 转换为隐式:

Action { request =>
  implicit val r = request
  Ok("Got request [" + request + "]")
}

我碰巧知道这是一个 Play 框架代码,但我不确定 Action 和 Ok 的签名是什么。我猜他们是这样的:

def Action(r:Request => Result):Unit
case class Ok(str:msg)(implicit r:Request)

同样,这纯粹是出于说明目的的猜测。

于 2012-10-02T07:28:44.113 回答
6

找了几个资源:

https://issues.scala-lang.org/browse/SI-1492

https://stackoverflow.com/a/5015161/480674

在第二个链接上搜索“闭包中的隐式参数”

于 2012-10-02T07:21:23.607 回答
5

在我的理解中,隐式的关键字意味着让编译器完成工作

声明一个隐式变量意味着它可以用于范围内其他方法的隐式参数。换句话说,编译器正在考虑使用该变量来填充隐式参数。

 def index = Action { implicit request =>
    val str = sayHi("Jason")
    Ok(views.html.index("Your new application is ready." + str))
  }

  private def sayHi(name: String)(implicit req: Request[AnyContent]) = name + ", you can the following content" + req.body

I declare an implicit parameter req in sayHi with type Request[AnyContent], however, I can call the method with only first parameter sayHi("Jason") because the implicit parameter req is filled in by the compiler to reference the implicit variable request

于 2016-01-01T19:49:40.710 回答