Why does "flatMap" work with Option sequences in Scala?

I cannot figure out how the Scala compiler determines how to use flatMapwith the Options sequence .

If I use flatMapfor 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 Options:

println(Seq(Some(1), None).flatMap(a => a)) // List(1)

So, it is flatMapconsidered Optionas a collection in this case. The question is, why does this work? flatMaphas 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 GenTraversableOncebut Optiondoes not inherit GenTraversableOnce. He inherits only Productand Serializable, and Productinherits Equals.

Scala flatMap Option ?

+4
1

. , , Option :

import scala.language.implicitConversions

/** 
    An implicit conversion that converts an option to an iterable value
*/

implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList

Option Iterable s.


, , flatten:

Seq(Some(1), None).flatten
+4

Source: https://habr.com/ru/post/1687109/


All Articles