这里是code for Option map method:
/** Returns a $some containing the result of applying $f to this $option's
* value if this $option is nonempty.
* Otherwise return $none.
*
* @note This is similar to `flatMap` except here,
* $f does not need to wrap its result in an $option.
*
* @param f the function to apply
* @see flatMap
* @see foreach
*/
@inline final def map[B](f: A => B): Option[B] =
if (isEmpty) None else Some(f(this.get))
因此,如您所见,如果选项不为空,它将使用函数返回的值映射到Some。这是code for Some class:
/** Class `Some[A]` represents existing values of type
* `A`.
*
* @author Martin Odersky
* @version 1.0, 16/07/2003
*/
@SerialVersionUID(1234815782226070388L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
def get = x
}
因此,如您所见,Some(null) 实际上会创建一个包含null 的Some 对象。您可能想要做的是使用Option.apply,如果值为null,它会返回None。这里是code for Option.apply method:
/** An Option factory which creates Some(x) if the argument is not null,
* and None if it is null.
*
* @param x the value
* @return Some(value) if value != null, None if value == null
*/
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
所以,你需要这样写代码:
Option("a").flatMap(s => Option.apply(null))
当然,这段代码没有意义,但我会认为你只是在做某种实验。