renegademonkey
renegademonkey

Reputation: 467

Scala: flatten mixed set of sets (or lists or arrays)

I have a Set which incorporates a combination of strings, and subSets of strings, like so:

val s = Set(brand1-_test, Set(brand-one, brand_one, brandone), brands-two, brandthree1, Set(brand-three2, brand_three2, brandthree2))

How do I flatten this so that I have one flat set of strings? s.flatten doesn't work with the following error:

error: No implicit view available from Object => scala.collection.GenTraversableOnce[B]

Neither does flatMap. What am I missing here? The Set could just as easily incorporate a subLists or subArrays (they are the result of a previous function), if that makes a difference.

Upvotes: 2

Views: 1337

Answers (2)

Dima
Dima

Reputation: 40500

 s.flatMap { case x:Iterable[_] => x; case y => Seq(y) }

Upvotes: 7

Assaf Mendelson
Assaf Mendelson

Reputation: 12991

Try putting it in a REPL:

scala> val s = Set("s1", Set("s2", "s3"))
s: scala.collection.immutable.Set[Object] = Set(s1, Set(s2, s3))

since you are providing two types (Set and String) then scala infers a type which covers both (Object in this case, but probably Any or AnyRef in most cases) which is not a collection and therefore cannot be flattened.

Upvotes: -1

Related Questions