St.Antario St.Antario - 25 days ago 6
Scala Question

Why can I invoke asJava once I added import import scala.collection.JavaConverters._

It looks quite strange to me. I didn't understand how it works. Consider the following example:

val m = Map("s" -> "s")
val jm : java.util.Map[String, String] = m.asJava // error
import scala.collection.JavaConverters._
val jm : java.util.Map[String, String] = m.asJava //fine


the method
asJava
is actually defined in
scala.collection.convert.Decorators::AsJava[A](op: => A)
. How can we invoke it on the
Scala
's
Map
?

Answer

There's an implicit conversion going on here. If you look at the code, you can see:

implicit def mapAsJavaMapConverter[A, B](m : Map[A, B]): AsJava[ju.Map[A, B]] =
    new AsJava(mapAsJavaMap(m))

so the compiler is wrapping your Map via the above, and the above will provide the asJava() method