Scala匿名函数中参数前的隐式关键字 [英] Implicit keyword before a parameter in anonymous function in Scala

查看:26
本文介绍了Scala匿名函数中参数前的隐式关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 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:

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?

推荐答案

这里有两个不同的功能.

There are two distinct features here.

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

First, request isn't really an argument in a method invocation. It's the argument of an anonymous function. The anonymous function itself is the argument of the method invocation.

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

Second, declaring an implicit argument in an anonymous function have the convenience of saving you from "forcing" a val into a implicit:

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

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

I happen to know this a Play framework code, but I am not sure what are the signatures for Action and 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.

这篇关于Scala匿名函数中参数前的隐式关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆