Search code examples
scalaflattenfor-comprehension

Flattening a Set of pairs of sets to one pair of sets


I have a for-comprehension with a generator from a Set[MyType] This MyType has a lazy val variable called factsPair which returns a pair of sets: (Set[MyFact], Set[MyFact]).

I wish to loop through all of them and unify the facts into one flattened pair (Set[MyFact], Set[MyFact]) as follows, however I am getting No implicit view available ... and not enough arguments for flatten: implicit (asTraversable ... errors. (I am a bit new to Scala so still trying to get used to the errors).

lazy val allFacts  =
(for {
  mytype <- mytypeList
} yield mytype.factsPair).flatten

What do I need to specify to flatten for this to work?


Solution

  • You won't be able to use flatten for this, because flatten on a collection returns a collection, and a tuple is not a collection.

    You can, of course, just split, flatten, and join again:

    val pairs = for {
      mytype <- mytypeList
    } yield mytype.factsPair
    val (first, second) = pairs.unzip
    val allFacts = (first.flatten, second.flatten)