Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Option.flatten in Scala

Tags:

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 ?

like image 671
Michael Avatar asked Mar 19 '14 15:03

Michael


People also ask

What is flatten in Scala?

flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.

How does Option work in Scala?

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.

What is option type in Scala?

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.

What is getOrElse in Scala?

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.


2 Answers

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
                     ^
like image 125
chemikadze Avatar answered Nov 16 '22 01:11

chemikadze


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]

like image 39
serejja Avatar answered Nov 16 '22 00:11

serejja