Search code examples
scaladictionaryimplicit

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?


Solution

  • 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.