Vikas Raturi
Vikas Raturi

Reputation: 926

Convert Set[Range] to Set[Int] in scala

I am trying to get set difference between two sets as follows:

val set1 = Set(1, 2, 3, 4, 5)
// gives:  scala.collection.immutable.Set[Int]
val set2 = Set(0 until 10)
// gives:  scala.collection.immutable.Set[scala.collection.immutable.Range]

However, the following gives error:

scala> set2.diff(set1)
<console>:14: error: type mismatch;
found   : scala.collection.immutable.Set[Int]
required: scala.collection.GenSet[scala.collection.immutable.Range]
      set2.diff(set1)
                ^

How to convert Set[Range] to Set[Int] in easiest way ?

Upvotes: 0

Views: 140

Answers (2)

acopeland
acopeland

Reputation: 76

Similarly to the answer suggested above

(0 until 10).toSet

also works and returns the same.

Upvotes: 0

Xavier Guihot
Xavier Guihot

Reputation: 61774

You could do this:

(0 to 10).toSet

or to stick with your initial idea (but less clean):

Set(0 until 10).flatten

which returns:

scala.collection.immutable.Set[Int] = Set(0, 5, 1, 6, 9, 2, 7, 3, 8, 4)

If you worked with a list you could do this (it doesn't seem to work for a Set):

List.range(0, 10)

Upvotes: 3

Related Questions