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

查看:71
本文介绍了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天全站免登陆