库对Scala的NotNull特性的支持 [英] Library support for Scala's NotNull trait
问题描述
注意::从Scala 2.11开始,不推荐使用NotNull
.
Notice: As of Scala 2.11, NotNull
is deprecated.
据我了解,如果您希望引用类型不可为空,则必须混入神奇的NotNull
特性,编译器会自动阻止您在其中添加null
-able值.例如,请参见此邮件列表线程.
As far as I understand, if you want a reference type to be non-nullable you have to mixin the magic NotNull
trait, and the compiler will automatically prevent you from putting null
-able values in it. See this mailing-list thread for instance.
缺少的是,对非空类型的不错的库支持.如果我想编写一个不需要直接连接Java代码的程序包,并且我想默认情况下阻止该程序包中的所有类型使用null
,我别无选择,只能重新定义所有构建变量,例如
What lacking is, a decent library support for non-nullable types. If I would like to write a package that don't need to interface java code directly, and I want to prevent all types in this package from using null
by default, I have no choice but to redefine all builting variables like so
//can't actually do that, but just to give the general idea
class NString extends String with NotNull
class NMap[X,Y] extends Map[X,Y] with NotNull
...
我希望scala具有(作为编译器插件或库)供我编写的选项
I expect scala to have (as a compiler plugin, or library) option for me to write
import collections.notnull._
以便轻松禁止在特定的scala文件中使用null
.
in order to easily disallow null
usage in a specific scala file.
是否可以轻松地将标准库中的许多有用类型强制为不可空?
Is there an option to easily force many usefull types in the standard library to be not-nullable?
推荐答案
我真的不知道与NotNull
达成的交易是什么,但是我得到的印象是Scala尚未完全解决它想如何交易的问题.与NotNull/Nullable概念.我自己的政策是永远不要在Scala中使用null,并且如果您调用可能返回null的Java API,请立即将其转换为Option
.
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)
然后您执行以下操作:
val foo: Option[Foo] = ?(getFooFromJavaAPIThatMightReturnNull())
我发现这比尝试跟踪可能为null或不为null的情况简单得多.
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...
更新:现在,最新的Scala版本在标准API中支持此功能:
Update: more recent Scala versions now support this in the standard API:
val foo: Option[Foo] = Option(getFooFromJavaAPIThatMightReturnNull())
这篇关于库对Scala的NotNull特性的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!