Search code examples
scalaapache-sparkjson4s

ClassCastException when converting json to "scala.collection.immutable.HashMap" when entries are less


I using json4s for converting a json to scala.collection.immutable.HashMap. But it fails with java.lang.ClassCastException: scala.collection.immutable.Map$Map3 cannot be cast to scala.collection.immutable.HashMap when entries in json are less than five. It works perfectly with five or more entries.

checked json is correct and this should not be issue.

implicit val formats = Serialization.formats(NoTypeHints)

read[scala.collection.immutable.HashMap[String, Config]](json).get(id)
case class Config(joinConfig: JoinConfig,
                         a: Option[Boolean],
                         b: Option[Boolean],
                         c: Option[Boolean]) {}

case class JoinConfig(d: Double,e: Double,f: Double) {}

Is this scala Map behavior or json4s issue?


Solution

  • This is Scala behavior. The Map.apply(pair: T*) returns special instances of Map based the size. A map with 3 elements does not require a hash table, its more efficient to just compare each key.

    As Yuriy says in his comment you should just use the Map trait and leave the implementation up to scala.