Conversion of Scala map containing Boolean to Java map containing java.lang.Boolean

左心房为你撑大大i 提交于 2019-12-04 10:43:20

问题


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?


回答1:


While JavaConversions will convert the Scala Map to a java.util.Map, and Scala implicitly converts scala.Boolean to java.lang.Boolean, Scala won't 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're doing this frequently 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



回答2:


scala.collection.JavaConversions isn't going to help you with the scala.Boolean to java.lang.Boolean problem. The following will work, though, using the boolean2Boolean method from scala.Predef:

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 Java's Boolean(boolean value) constructor:

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 just 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


来源:https://stackoverflow.com/questions/9638492/conversion-of-scala-map-containing-boolean-to-java-map-containing-java-lang-bool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!