I am trying to convert a java.util.Map to a Map[String, Any]. I get the java map as part of my java interface.
I am running into problems with conversions of Integer to Int and java.lang.Long to scala.Long.
code is as follows:
import java.math.{BigDecimal => JavaBigDecimal}
import scala.collection.JavaConverters.mapAsScalaMapConverter
import scala.collection.mutable
val input = new java.util.HashMap[String, Object]()
input.put("test", Integer.valueOf(1))
input.put("test2", new JavaBigDecimal("12"))
val scalaMap = input.asScala
//noinspection ScalaStyle
val filter: mutable.Map[String, Object] = scalaMap.filter(_._2 != null)
val toMap: Map[String, Any] = filter.toMap
val initialContext = toMap.mapValues {
case b: JavaBigDecimal => BigDecimal(b)
case i: Integer => Integer2int(i)
case l: java.lang.Long => l.toLong
case a: Any if a == null => None
case a: Any if a != null => a
}
initialContext.get("test").get.getClass
initialContext.get("test2").get.getClass
The result of the last 2 lines is:
res3: Class[?0] = class java.lang.Integer
res4: Class[?0] = class scala.math.BigDecimal
The BigDecimal does what I expect it to do, but Int (and also Long), do not. It seems to get magically converted back into Integer. Also when I just add a different static number:
case i: Integer => 42
it will turn this into an Integer
I need this Class information though, because deeper into my java API I do a check if the expected type matches the gotten type and Int (expected) does not match Integer.
classOf[Int] == classOf[Integer]will return false, same fortypeOf. In some casesInterases toIntegerat runtime, but not always.