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

后端 未结 2 583
长情又很酷
长情又很酷 2021-02-07 10:59

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


        
2条回答
  •  星月不相逢
    2021-02-07 11:43

    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
    

提交回复
热议问题