Convert a Scala map containing a Boolean to Java map containing java.lang.Boolean

I would 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 

failure:

 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 

Implicit conversions JavaConversions work with containers parameterized on the same types, but are not aware of the conversion between Boolean and java.lang.Boolean.

Can I use JavaConversions magic for this conversion or is there a short syntax for the conversion without using implicit conversions in this package?

+8
java scala interop
source share
2 answers

While JavaConversions converts the Scala map to java.util.Map , and Scala implicitly converts scala.Boolean to java.lang.Boolean , Scala will not perform two implicit conversions to get the type you want.

Boolean provides a box method for explicit conversion.

 val b: java.util.Map[Int, java.lang.Boolean] = a.mapValues(Boolean.box) 

If you often do this in your code, you can define your own implicit conversion for all Map[T, Boolean] .

 import scala.collection.JavaConversions._ implicit def boolMap2Java[T](m: Map[T, Boolean]): java.util.Map[T, java.lang.Boolean] = m.mapValues(Boolean.box) val b: java.util.Map[Int, java.lang.Boolean] = a 
+8
source share

scala.collection.JavaConversions will not help you with the scala.Boolean to java.lang.Boolean problem. However, the following will work: boolean2Boolean scala.Predef method:

 val a = Map[Int, Boolean](1 -> true, 2 -> false) val b: java.util.Map[Int, java.lang.Boolean] = a.mapValues(boolean2Boolean) 

Or you can use the Java constructor Boolean(boolean value) :

 val a = Map[Int, Boolean](1 -> true, 2 -> false) val b: java.util.Map[Int, java.lang.Boolean] = a.mapValues(new java.lang.Boolean(_)) 

Or you can simply declare the first map to use the Java reference type:

 val a = Map[Int, java.lang.Boolean](1 -> true, 2 -> false) val b: java.util.Map[Int, java.lang.Boolean] = a 
+8
source share

All Articles