Why Some(null) isn't considered None?

前端 未结 6 1870
感动是毒
感动是毒 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:17

    I think the others in the thread do a good job explaining why Some(null) "should" exist, but if you happen to be getting Some(null) somewhere and want a quick way to turn it into None, I've done this before:

    scala> val x: Option[String] = Some(null)
    x: Option[String] = Some(null)
    
    scala> x.flatMap(Option(_))
    res8: Option[String] = None
    

    And when the starting Option is a legit non-null value things work as you probably want:

    scala> val y: Option[String] = Some("asdf")
    y: Option[String] = Some(asdf)
    
    scala> y.flatMap(Option(_))
    res9: Option[String] = Some(asdf)
    

提交回复
热议问题