简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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