简体   繁体   English

从函数返回的映射中获取值,并在Scala中进行隐式处理

[英]Get value from map returned from function with implicit in Scala

Having an implicit value and function defined as follows 具有如下定义的隐式值和函数

implicit val v = 0

def function(implicit v: Int): Map[String, String] = Map("key" -> "value")

I can do 我可以

function.get("key") // res0: Option[String] = Some(value)
function(v)("key") // res0: String = value

but the following doesn't compile 但以下内容无法编译

function("key")

So how can I in one go access a map using parentheses and pass implicit parameter? 那么,我该如何使用括号访问地图并传递隐式参数呢?

Here are your options: 这是您的选择:

scala> function.apply("key")
res6: String = value

scala> function(implicitly)("key")
res7: String = value

As compiler can't know if you want to pass an implicit parameter explicitly or call apply method, designers decided it will mean passing the implicit parameter. 由于编译器无法知道是要显式传递隐式参数还是调用apply方法,因此设计人员认为这意味着传递隐式参数。

You can either give up on using the syntactic sugar and just use apply that will resolve ambiguity or you can pass the parameter explicitly, but let the compiler find the value. 您可以放弃使用语法糖,而只使用可以解决歧义的apply ,或者可以显式传递参数,但让编译器找到值。

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

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