bzak
bzak

Reputation: 495

Scala: Invoking Standard Methods on Wrapper Maps After Java to Scala Conversion

I have two java maps which map a String to a set of Strings.

I want to convert the java maps to Scala and "add" map1 to map2 such that if they both have the same keys the value in the resultant map will be the union of the 2 value sets. I found a nice solution for the map addition:

map1 ++ map2.map { case (k,v) => k -> (v ++ map1.getOrElse(k,v))}

The issue happens when I convert the java maps to Scala via the 'asScala' call. When we do this conversation we get:

enter image description here

After the conversion to Scala, I am no longer able to run the solution above on these wrapper collections. The ++ operation on the map is still defined. However the SetWrapper class does not define a ++ operation. As far as I can tell the SetWrapper does not define any operations at all! Here is the full definition from the docs:

enter image description here

SetWrapper seems to extend an abstract class and does not define any of the functionality.

How can I get around this issue? Is there another conversation step to a real Set object?

Upvotes: 1

Views: 365

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

JMapWrapper wraps a Java Map in a Scala Map; SetWrapper wraps a Scala Set in a Java Set. So it has Java's methods for Set, not Scala's.

You don't provide types, but it appears you start with a java.util.Map[SomeKey, java.util.Set[SomeType]]. Calling asScala on it will only convert the outer Map, not its values. You can fix this by using javaMap.asScala.mapValues(_.asScala) (with the usual caveat that it will call asScala each time a value is accessed; use .map instead if this isn't acceptable).

Upvotes: 3

Related Questions