对 Scala 的 NotNull 特征的库支持
注意:从 Scala 2.11 开始,NotNull
已被弃用。
据我了解,如果您希望引用类型不可为空,则必须混合神奇的 NotNull
特征,编译器会自动阻止您放置 null
- 可以值在里面。例如,请参阅此邮件列表线程。
缺少的是对不可空类型的良好库支持。如果我想写一个不需要直接接口java代码的包,并且我想阻止这个包中的所有类型默认使用null
,我别无选择,只能重新定义所有像这样构建变量
//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 有(作为编译器插件或库)选项供我编写,
import collections.notnull._
以便轻松禁止在特定 scala 文件中使用 null
。
是否有一个选项可以轻松强制标准库中的许多有用类型不可为空?
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 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.
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
...
I expect scala to have (as a compiler plugin, or library) option for me to write
import collections.notnull._
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我真的不知道
NotNull
到底是怎么回事,但我的印象是 Scala 还没有完全弄清楚它要如何处理 NotNull/Nullable 概念。我自己的政策是永远不要在 Scala 中使用 null,如果您调用可能返回 null 的 Java API,请立即将其转换为Option
。这个实用方法是我最好的朋友:
然后你做这样的事情:
我发现这比尝试跟踪可能为空或不为空的内容要简单得多。
所以我根本没有回答你的问题,但我把它传递给它,以防它有用...
更新:更新的 Scala 版本现在在标准 API 中支持这一点:
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 anOption
.This utility method is my best friend:
Then you do stuff like this:
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: