I cannot figure out how the Scala compiler determines how to use flatMap
with the Option
s sequence .
If I use flatMap
for sequence sequences:
println(Seq(Seq(1), Seq()).flatMap(a => a)) // List(1)
it will concatenate all nested sequences
The same thing happens if I use it with the sequence Option
s:
println(Seq(Some(1), None).flatMap(a => a)) // List(1)
So, it is flatMap
considered Option
as a collection in this case. The question is, why does this work? flatMap
has the following definition:
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That
The value that the function that returns the instance expects GenTraversableOnce
but Option
does not inherit GenTraversableOnce
. He inherits only Product
and Serializable
, and Product
inherits Equals
.
Scala flatMap
Option
?