Null-safety
Kotlin 的一项主要特性是 空安全,它在编译时干净利落地处理 null
值,而不是在运行时遇到著名的 NullPointerException
。通过空值声明和表达 “value or no value” 语义,这使应用程序更加安全,而无需付出包装器的代价,例如 Optional
。(Kotlin 允许使用具有空值的函数构造。请参见 Kotlin 空安全的综合指南。)
One of Kotlin’s key features is null-safety,
which cleanly deals with null
values at compile time rather than bumping into the famous
NullPointerException
at runtime. This makes applications safer through nullability
declarations and expressing “value or no value” semantics without paying the cost of wrappers, such as Optional
.
(Kotlin allows using functional constructs with nullable values. See this
comprehensive guide to Kotlin null-safety.)
尽管 Java 无法让您在类型系统中表达空安全,但 Spring Framework 通过在 org.springframework.lang
包中声明的工具友好型注解提供了 null-safety of the whole Spring Framework API。默认情况下,Kotlin 中使用的 Java API 的类型都被视为 平台类型,对它们的空值检查是宽松的。https://kotlinlang.org/docs/java-interop.html#jsr-305-support[Kotlin 对 JSR-305 注解的支持] 和 Spring 空值注解为 Kotlin 开发人员提供了整个 Spring Framework API 的空安全,优点是在编译时处理与 null
相关的问题。
Although Java does not let you express null-safety in its type-system, the Spring Framework
provides null-safety of the whole Spring Framework API
via tooling-friendly annotations declared in the org.springframework.lang
package.
By default, types from Java APIs used in Kotlin are recognized as
platform types,
for which null-checks are relaxed.
Kotlin support for JSR-305 annotations
and Spring nullability annotations provide null-safety for the whole Spring Framework API to Kotlin developers,
with the advantage of dealing with null
-related issues at compile time.
Reactor 或 Spring Data 等库提供了空安全 API 来利用此功能。 |
Libraries such as Reactor or Spring Data provide null-safe APIs to leverage this feature. |
你可以通过添加 -Xjsr305
编译器标志来配置 JSR-305 检查,并带有以下选项:-Xjsr305={strict|warn|ignore}
。
You can configure JSR-305 checks by adding the -Xjsr305
compiler flag with the following
options: -Xjsr305={strict|warn|ignore}
.
对于 Kotlin 版本 1.1+,默认行为与 -Xjsr305=warn
相同。需要 strict
值来考虑 Spring API NULL 安全性,该 NULL 安全性是从 Spring API 推断的 Kotlin 类型,但应注意,Spring API NULL 安全性声明甚至在次版本之间也可能会发生变化,将来可能会添加更多检查。
For kotlin versions 1.1+, the default behavior is the same as -Xjsr305=warn
.
The strict
value is required to have Spring Framework API null-safety taken into account
in Kotlin types inferred from Spring API but should be used with the knowledge that Spring
API nullability declaration could evolve even between minor releases and that more checks may
be added in the future.
尚不支持泛型类型参数、变长参数和数组元素空值性,但应该在即将发布的版本中支持这些功能。有关最新信息,请参见 此讨论。 |
Generic type arguments, varargs, and array elements nullability are not supported yet, but should be in an upcoming release. See this discussion for up-to-date information. |