Adrian Daniel Culea
Adrian Daniel Culea

Reputation: 181

Cannot cast java ArrayList to scala immutable List

I have the following data structure:

java.util.Map[List[String],List[String]] = {[10, 20]=[1500], [5, 7]=[1400]}

I am trying to extract the numbers 10 20 5 and 7 using Scala. The way I was looking to achieve this is:

map.head._1 -> to extract 10 (map.head returns a tuple)
map.head._2 -> to extract 20 (map.head returns a tuple)

However, I am getting the following exception:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to scala.collection.immutable.List

I have read about importing import scala.collection.JavaConversions._ however, this did not fix anything.

Thanks, any help is highly appreciated!

The piece of code that tries to achieve this is:

 def getTokenRangeForKeys(params: String): java.util.Map[List[String], List[String]] = {
    invokeOperation[java.util.Map[List[String], List[String]]]("XXX", "YYY", Array(params))
  }

The above method returns my map, which looks like this:

  map = java.util.Map[List[String],List[String]] = {[10, 20]=[1500], [5, 7]=[1400]}

What I have tried so far:

map.head._1 -> java.lang.ClassCastException: java.util.ArrayList cannot be cast to scala.collection.immutable.List

scalaMap = map.asScala
m.headOption match {
  case Some((h1, h2)) => println((h1, h2)) -> java.util.ArrayList cannot be cast to scala.collection.immutable.List
  case None => ...
}

Upvotes: 2

Views: 8163

Answers (2)

Suma
Suma

Reputation: 34413

I think your declaration of what comes from Java world should be:

java.util.Map[java.util.List[String], java.util.List[String]]

In the current form of java.util.Map[List[String], List[String]] you declare a java Map of Scala Lists, which is probably not what you want. JVM is not complaining when you pass your Java types because only top level type is checked as a part of function signature check - this is called type erasure.

On this you should use JavaConverters asScala to convert to corresponding Scala types as written in the Reactormonk answer:

import scala.collection.JavaConverters._
val m = map.asScala.map{case (h, k) => (h.asScala, k.asScala)}

Upvotes: 3

Reactormonk
Reactormonk

Reputation: 21700

Don't use JavaConversions.

import scala.collection.JavaConverters._
val m = map.asScala.map({case (h, k) => (h.asScala, k.asScala)})
m.headOption match {
  case Some((h1, h2)) => ...
  case None => ...
}

Upvotes: 0

Related Questions