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

后端 未结 2 573
长情又很酷
长情又很酷 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:45

    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
    

提交回复
热议问题