简体   繁体   English

Scala中匿名函数中参数之前的隐式关键字

[英]Implicit keyword before a parameter in anonymous function in Scala

I understand implicit parameters and implicit conversions in Scala but I saw this for the first time today: the implicit keyword in front of a parameter in an anonymous function: 我了解Scala中的隐式参数和隐式转换,但是今天我第一次看到了这一点:匿名函数中参数前面的隐式关键字:

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

What does the implicit keyword do here? 隐式关键字在这里做什么?

Are there resources on the web that describes more on what the use case is? Web上是否有资源描述用例是什么?

There are two distinct features here. 这里有两个不同的功能。

First, request isn't really an argument in a method invocation. 首先, request实际上不是方法调用中的参数。 It's the argument of an anonymous function. 这是匿名函数的参数。 The anonymous function itself is the argument of the method invocation. 匿名函数本身是方法调用的参数。

Second, declaring an implicit argument in an anonymous function have the convenience of saving you from "forcing" a val into a implicit: 其次,在匿名函数中声明隐式参数具有避免将val“强制”转换为隐式的便利:

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

I happen to know this a Play framework code, but I am not sure what are the signatures for Action and Ok. 我碰巧知道这是一个Play框架代码,但是我不确定Action和Ok的签名是什么。 I will guess that they are something like that: 我猜他们是这样的:

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

Again, it's pure guessing for illustrative purposes only. 再次,这纯粹是出于说明目的。

Found a few resources: 找到了一些资源:

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

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

search for "Implicit arguments in closures" on the second link 在第二个链接上搜索“闭包中的隐式参数”

In my understanding, the keyword of Implicit means Let complier do the job 在我的理解中,隐式关键字的意思是让编译器完成任务

Declaring an implicit variable means it can be used for implicit parameter of other methods inside the scope. 声明隐式变量意味着可以将其用于范围内其他方法的隐式参数。 In other words, the variable is being considered by the compiler to fill in implicit parameters. 换句话说,编译器正在考虑使用变量来填充隐式参数。

 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 我在类型为Request[AnyContent] sayHi声明了隐式参数req ,但是,我只能使用第一个参数sayHi("Jason")调用该方法,因为编译器会填充隐式参数 req来引用隐式变量 request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM