Reputation: 183
I'm new to scala,
val data = Map("test" -> data1,
"cat" -> None,
"myList" -> Map("test2" -> data2, "test3" -> data3))
val output = data.map(x =>
if (x._2.isInstanceOf[Map[String, Any]]) (x._1 -> Some(x._2))
else x)
Map(test -> data1,
cat -> None,
myList -> Some(Map(test2 -> data2, test3 -> data3)))
val valueToFieldMapping = output(fieldName).get.asInstanceOf[Map[String, String]]
I'm getting
java.lang.ClassCastException: scala.Some cannot be cast to scala.collection.immutable.Map
exception please help me if anyone has an idea about this. Thanks
Upvotes: 2
Views: 13036
Reputation: 27356
Firstly, let's clean up the definition of output
by using mapValues
:
val output = data.mapValues(x =>
if (x.isInstanceOf[Map[String, Any]]) Some(x)
else x)
Then do this
val valueToFieldMapping = output(fieldName).asInstanceOf[Option[Map[String, String]]].get
You can't call get
on the Some
you generate when creating output
because the compile doesn't know it is an Option
yet.
Having said all that, the comments are right in saying that using Any
and asInstanceOf
is really ugly so you need to find a better way of expressing whatever it is you are trying to do. At the very least, use match
rather than asInstanceOf
so that you can implement the error case if the object is not what you think it is.
Upvotes: 1
Reputation: 2686
The problem is with this line you don't have .get property on instance of Object. you don't need .get if you want to use .get method then do output.get(fieldName)
val valueToFieldMapping = output(fieldName).get.asInstanceOf[Map[String, String]]
output.get(fieldName)
gives you the Option[Object]
and you are trying to convert object into the instance of the Map[String, String]
there is no implicit conversion from Option to map so that's the reason you are getting the error:
java.lang.ClassCastException: scala.Some cannot be cast to scala.collection.immutable.Map
or you can do like this:
val valueToFieldMapping: Option[Map[String, String]] = output.get(fieldName).asInstanceOf[Option[Map[String, String]]]
Upvotes: 1