Well ... the first thing I will say is that "When in Scala -land, stay away from the null monster whenever possible." They are dangerous.
Now ... to understand this behavior, the first thing you need to try in Scala -shell is the following,
scala> val n = null n: Null = null
So ... Scala null has an instance of this null class.
Now ... let's see what happens when we mix this null with Option ,
scala> val nullOpt1 = Option(null) nullOpt1: Option[Null] = None scala> val nullOpt2 = Some(null) nullOpt2: Some[Null] = Some(null)
Notice the difference ... between the two ... So basically Scala people thought there might be people who want to wrap null in Option ... so they let them explicitly use Some.apply to wrap this null in Option Where, when the use of Option.apply behaves more "reasonably" and gives you None when trying to wrap null .
Now ... first, let's see how map implemented for Option ,
final def map[B](f: A => B): Option[B] = if (isEmpty) None else Some(f(this.get))
And now ... it should be clear that "why Some(null).map((x: String) => x) gives you Some(null) ?".
As for understanding for ... cases, which will require little understanding of how for implemented for Option using Repr . And the behavior will become clear.
source share