I'd like to convert a scala map with a Boolean value to a java map with a java.lang.Boolean value (for interoperability).
import scala.collection.JavaConversions._
val a = Map[Int, Boolean]( (1, true), (2, false) )
val b : java.util.Map[Int, java.lang.Boolean] = a
fails with:
error: type mismatch;
found : scala.collection.immutable.Map[Int,scala.Boolean]
required: java.util.Map[Int,java.lang.Boolean]
val b : java.util.Map[Int, java.lang.Boolean] = a
The JavaConversions implicit conversions work happily with containers parameterized on the same types, but don't know about the conversion between Boolean & java.lang.Boolean.
Can I use the JavaConversions magic to do this conversion, or is there a concise syntax for doing the conversion without using the implicit conversions in that package?
While
JavaConversions
will convert the Scala Map to ajava.util.Map
, and Scala implicitly convertsscala.Boolean
tojava.lang.Boolean
, Scala won't perform two implicit conversions to get the type you want.Boolean
provides abox
method for explicit conversion.If you're doing this frequently in your code, you can define your own implicit conversion for all
Map[T, Boolean]
.scala.collection.JavaConversions
isn't going to help you with thescala.Boolean
tojava.lang.Boolean
problem. The following will work, though, using theboolean2Boolean
method fromscala.Predef
:Or you can use Java's
Boolean(boolean value)
constructor:Or you can just declare the first map to use the Java reference type: