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 ?
flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value.
As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.
This is common practice to constrain some methods to be executed against particular types. Actually, <:<
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 = ...
So that, implicit of type <:<[A, B]
can be resolved only if A is a subtype of B.
In this case, it can be resolved only if Option
in wrapped in another Option
. In any other cases, compile error will occur:
scala> Option(42).flatten
<console>:8: error: Cannot prove that Int <:< Option[B].
Option(42).flatten
^
As ScalaDoc says - An instance of A <:< B witnesses that A is a subtype of B
.
So in this case an Option
can be flattened only if it contains another Option
inside.
An Option[Option[String]]
flattens to an Option[String]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With