2023-04-19 23:26:16 +08:00
|
|
|
[[kotlin-null-safety]]
|
|
|
|
= Null-safety
|
|
|
|
|
2023-11-21 22:59:24 +08:00
|
|
|
One of Kotlin's key features is {kotlin-docs}/null-safety.html[null-safety],
|
2023-04-19 23:26:16 +08:00
|
|
|
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
|
2023-11-21 22:59:24 +08:00
|
|
|
{baeldung-blog}/kotlin-null-safety[comprehensive guide to Kotlin null-safety].)
|
2023-04-19 23:26:16 +08:00
|
|
|
|
|
|
|
Although Java does not let you express null-safety in its type-system, the Spring Framework
|
2023-04-19 23:26:17 +08:00
|
|
|
provides xref:languages/kotlin/null-safety.adoc[null-safety of the whole Spring Framework API]
|
2023-04-19 23:26:16 +08:00
|
|
|
via tooling-friendly annotations declared in the `org.springframework.lang` package.
|
|
|
|
By default, types from Java APIs used in Kotlin are recognized as
|
2023-11-21 22:59:24 +08:00
|
|
|
{kotlin-docs}/java-interop.html#null-safety-and-platform-types[platform types],
|
2023-04-19 23:26:16 +08:00
|
|
|
for which null-checks are relaxed.
|
2023-11-21 22:59:24 +08:00
|
|
|
{kotlin-docs}/java-interop.html#jsr-305-support[Kotlin support for JSR-305 annotations]
|
2023-04-19 23:26:16 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
NOTE: Libraries such as Reactor or Spring Data provide null-safe APIs to leverage this feature.
|
|
|
|
|
|
|
|
You can configure JSR-305 checks by adding the `-Xjsr305` compiler flag with the following
|
|
|
|
options: `-Xjsr305={strict|warn|ignore}`.
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
NOTE: Generic type arguments, varargs, and array elements nullability are not supported yet,
|
2023-11-21 22:59:24 +08:00
|
|
|
but should be in an upcoming release. See {kotlin-github-org}/KEEP/issues/79[this discussion]
|
2023-04-19 23:26:16 +08:00
|
|
|
for up-to-date information.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|