Why Some(null) isn't considered None?

前端 未结 6 1873
感动是毒
感动是毒 2020-12-15 02:38

I am curious:

scala> Some(null) == None
res10: Boolean = false

Why isn\'t Some(null) transformed to None?

6条回答
  •  遥遥无期
    2020-12-15 03:13

    Unfortunately, null is a valid value for any AnyRef type -- a consequence of Scala's interoperability with Java. So a method that takes an object of type A and, internally, store it inside an Option, might well need to store a null inside that option.

    For example, let's say you have a method that takes the head of a list, checks if that head correspond to a key in a store, and then return true if it is. One might implement it like this:

    def isFirstAcceptable(list: List[String], keys: Set[String]): Boolean =
        list.headOption map keys getOrElse false
    

    So, here's the thing... if the that inside list and keys come from some Java API, they both may well contain null! If Some(null) wasn't possible, then isFirstAcceptable(List[String](null), Set[String](null)) would return false instead of true.

提交回复
热议问题