Understanding Option.flatten in Scala

I noticed that Option.flatten is defined as follows:

  def flatten [B] (implicit ev: A <: <Option [B]): Option [B] =
     if (isEmpty) None else ev (this.get)

What is ev here? What does A <:< Option[B] mean? What is it used for?

+7
scala
source share
3 answers

It is common practice to limit certain methods that must be performed against certain types. In fact, <:< is a type defined in scala.Predef as follows:

 @implicitNotFound(msg = "Cannot prove that ${From} <:< ${To}.") sealed abstract class <:<[-From, +To] extends (From => To) with Serializable ... implicit def conforms[A]: A <:< A = ... 

Thus, the implicit type <:<[A, B] can only be allowed if A is a subtype of B.

In this case, it can only be allowed if Option wrapped in another Option . In any other cases, a compilation error will occur:

 scala> Option(42).flatten <console>:8: error: Cannot prove that Int <:< Option[B]. Option(42).flatten ^ 
+11
source share

As ScalaDoc says - An instance of A <:< B witnesses that A is a subtype of B

So, in this case, a Option can be smoothed out only if it contains another Option inside.

An Option[Option[String]] aligns to Option[String]

+3
source share

<:< - this is a “generalized type restriction” or “evidence type”. They are supplied by the compiler and can be used to further limit general type parameters. In this case, the restriction is that type A must be a subtype of Option[B] , i.e. An option is a nested option [Option [T]] for some type T

+2
source share

All Articles