Library support for Scala's NotNull trait

后端 未结 1 714
误落风尘
误落风尘 2021-02-05 14:09

Notice: As of Scala 2.11, NotNull is deprecated.

As far as I understand, if you want a reference type to be non-nullable you have to mixin

相关标签:
1条回答
  • 2021-02-05 14:32

    I don't really know what the deal is with NotNull, but I get the impression that Scala hasn't fully worked out how it wants to deal with NotNull/Nullable concepts. My own policy is to never use null in Scala, and if you call a Java API that may return null, immediately convert it to an Option.

    This utility method is my best friend:

    def ?[A <: AnyRef](nullable: A): Option[A] = if (nullable eq null) None else Some(nullable)
    

    Then you do stuff like this:

    val foo: Option[Foo] = ?(getFooFromJavaAPIThatMightReturnNull())
    

    I find this far simplier than trying to track what may or may not be null.

    So I didn't answer your question at all, but I pass this on in case it's useful...

    Update: more recent Scala versions now support this in the standard API:

    val foo: Option[Foo] = Option(getFooFromJavaAPIThatMightReturnNull())
    
    0 讨论(0)
提交回复
热议问题