Jeff Hu
Jeff Hu

Reputation: 744

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.

Upvotes: 2

Views: 1354

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Simpler and neat Solution

preferences.valuesIterator.flatten.toSet

Get all the values of the preferences map using valuesIterator and then flatten and then convert to set using toSet function.

getAllSlots function becomes

def getAllSlots(preferences: Map[Band, List[Slot]]): Set[Slot] = 
  preferences.valuesIterator.flatten.toSet

Upvotes: 2

Ende Neu
Ende Neu

Reputation: 15783

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
  }}
}

Upvotes: 4

Related Questions