Jeff Hu Jeff Hu - 9 months ago 59
Scala Question

Scala's Empty Set: ... doesn't conform to expected type Set[Nothing]

I am new to Scala's Set. I was trying to concatenate a Set with an empty Set. The code follows:

def getAllSlots(preferences: Map[Band, List[Slot]]): Set[Slot] = {
preferences.foldLeft(Set.empty){(r,c) => c match {
case (_, li) => li.toSet ++ r
case _ => r
}}
}


The error happened when I am trying to do
li.toSet ++ r
, complaining that
... doesn't conform to expected type Set[Nothing]
. Then, I have no idea how to build up a Set starting from an empty one.

Thanks everyone.

Answer Source

You have to help the compiler to infer the right type, it doesn't have enough informations to figure out that you mean Set[Slot], empty takes a type parameter:

def getAllSlots(preferences: Map[Band, List[Slot]]): Set[Slot] = {
  preferences.foldLeft(Set.empty[Slot]){(r,c) => c match {
    case (_, li) => li.toSet ++ r
    case _ => r
  }}
}