有计划在Java中添加经过类型检查的可空类型吗?

huangapple go评论67阅读模式
英文:

Are there plans to add type-checked nullable types to Java?

问题

关于Kotlin相对于Java的一个我喜欢的特性是,你可以使用编译器来确保某些值永远不会为null。(Swift也具有这个特性。)

var foo: Thing
var bar: Thing?

在这个示例中,foo 永远不会为null。我不需要在代码中添加繁琐的空指针检查。另一方面,bar 可能为null。还有一种方便的语法来检查某个值是否为null并使用它。

bar?.x             // 如果 bar 为null,则为null;否则为 bar.x
bar ?: defaultBar  // 如果 bar 为null,则为 defaultBar;否则为 bar
if (bar != null) { 
    // 此处的 bar 现在是 Thing 类型,而不是 Thing?(假设 bar 是参数或局部变量。)
}

近来Java的发展速度加快,不断添加新特性,但我没有听说过类似的特性。这个特性是否曾经被考虑过并被拒绝了?或者它将来可能会被添加到Java中吗?

英文:

One of my favorite things about Kotlin, relative to Java, is that you can use the compiler to guarantee that certain values are never null. (Swift also has this feature.)

 var foo: Thing 
 var bar: Thing?

Is that example, foo can never be null. I don't have to pollute my code with of defensive null checks. On the other hand, bar could be null. There is also convenient syntax for checking if something is null and using it.

bar?.x             // bar.x, or null if bar is null
bar ?: defaultBar  // bar, or defaultBar if bar is null
if (bar != null) { 
    // bar is now Thing here, not Thing? (Assuming bar is a parameter or local variable.)
}

Java has been moving faster lately, and adding features, but I haven't heard anything about this. Was it considered and rejected? Or might it someday be added to Java?

答案1

得分: 2

不,Oracle没有这样的计划。

Oracle认为您可以使用第三方工具来完成,例如Checker FrameworkNullAway,或者集成在IDE(如IntelliJ或Eclipse)中的支持。

Oracle甚至不支持创建所有第三方工具都会使用的标准@NonNull注释。Oracle让JSR 305,本应定义标准注释的项目过期,并且没有重新启动它。

英文:

No, Oracle has no such plans.

Oracle feels that you can use a third-party tool to do so, such as the Checker Framework, NullAway, or support built into an IDE such as IntelliJ or Eclipse.

Oracle doesn't even support the creation of a standard @NonNull annotation that all third-party tools would use. Oracle let JSR 305, which would have defined standard annotations, expire and has not revived it.

答案2

得分: 0

Objects类中有3个静态方法,用于要求对象不为空,如果为空则抛出异常:

  • requireNonNull(T obj)
  • requireNonNull(T obj, String message)
  • requireNonNull(T obj, Supplier<String> messageSupplier)
英文:

There are 3 static methods in Objects class for requiring object to be not null and throwing exception if it is:

requireNonNull(T obj)

requireNonNull(T obj, String message)

requireNonNull(T obj, Supplier&lt;String&gt; messageSupplier)

答案3

得分: 0

就像 @mernst 指出的那样,你可以使用 Checker Framework。它会在编译时检查所有内容,你甚至可以添加自己的检查器。

英文:

Like @mernst pointed out, you can use the Checker Framework. It checks everything at compile time and you can even add your own checker.

huangapple
  • 本文由 发表于 2020年5月5日 01:36:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定