Call to flatten fails to compile on one use case but works on the other

Viewed 812

I want to flatten a sequence of sets:

val test = for(i <- 1 to 3) yield {
  if(i == 1)
    Set.empty
  else
    Set(9, 1)
}
val b = test.flatten

This fails with:

ScalaFiddle.scala:7: error: No implicit view available from scala.collection.immutable.Set[_ <: Int] => scala.collection.GenTraversableOnce[B]. val b = test.flatten ^ ScalaFiddle.scala:7: error: not enough arguments for method flatten: (implicit asTraversable: scala.collection.immutable.Set[_ <: Int] => scala.collection.GenTraversableOnce[B])scala.collection.immutable.IndexedSeq[B]. Unspecified value parameter asTraversable. val b = test.flatten

But what really confuses me is why does this work?:

val test = for(i <- 1 to 3) yield {
  if(i == 1)
    Set.empty
  else
    Set(9, 1)
}
println(test.flatten)
// compiles and prints Vector(9, 1, 9, 1) when run

So to my question: What's the difference between the flatten in println(test.flatten) and the call to flatten in val b = test.flatten?

2 Answers
Related