user77323 user77323 - 3 months ago 37
Scala Question

Expression of type scala.collection.Set[scala.Predef.String] doesn't conform to expected type scala.Predef.Set[scala.Predef.String]

I'm relatively new to programming and am enjoying using Scala to teach myself. I've come across a problem that I can't seem to wrap my head around.

Here is the snippet of code I'm trying to work on. All the Maps used are mutable.Map[String, Any]

def CreateCompleteVoterSet(): Set[String] =


{

val firstSet = concedeVoterMap.keySet.diff(voterMap.keySet)
val secondSet = emoteVoterMap.keySet.diff(voterMap.keySet)
val thirdSet = speedVoterMap.keySet.diff(voterMap.keySet)
var finalSet = voterMap.keySet ++ firstSet ++ secondSet ++ thirdSet

return finalSet


}

The error it gives me is: Expression of type scala.collection.Set[scala.Predef.String] doesn't conform to expected type scala.Predef.Set[scala.Predef.String]

I'm sure I could find some way to force it to the same type, possibly with toSet(), but I'm confused by what the error is. Could someone give me some insight on why the error is happening and point me in the right direction for a safe way to fix it?

Answer

Because there is no import for Set, Set[String] means scala.Predef.Set (scala.Predef._ is imported automatically in all Scala files). This is an alias for scala.collection.immutable.Set. But keySet method of scala.collection.mutable.Map returns a scala.collection.Set, which is a supertype of scala.collection.immutable.Set (and of scala.collection.mutable.Set, which isn't really relevant to the question). Combining scala.collection.Sets with ++ still gives you a scala.collection.Set.

The simple solution would be to change the return type to scala.collection.Set, unless you actually require a scala.collection.immutable.Set for other reasons.