为了解决这个问题,文档建议使用 Optional<Page<T>> 作为返回值类型,允许使用 Optional 来表示空结果的可能性。

Null Safety

Kotlin 的主要特性之一是 ,它在编译时清楚处理值。这通过非空声明和语义的表达而使应用程序更加安全,而不需要类似于的包装器的开销。(Kotlin 允许使用带有可空值的功能结构。请参阅此 ``。)

One of Kotlin’s key features is null safety, which cleanly deals with null values at compile time. This makes applications safer through nullability declarations and the expression of “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 Data API 使用声明于 包中的 @ 工具友好注释进行注释。默认情况下,Kotlin 中使用的 Java API 的类型被识别为 ,对于此类类型,空检查是宽松的。 和 Spring 非空注释为 Kotlin 开发人员提供整个 Spring Data API 的空安全,其优势在于在编译时处理 `` 相关问题。

Although Java does not let you express null safety in its type system, Spring Data API is annotated with JSR-305 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 Data API to Kotlin developers, with the advantage of dealing with null related issues at compile time.

参阅 Null Handling of Repository Methods 来了解空安全如何应用到 Spring Data 存储库。

See Null Handling of Repository Methods how null safety applies to Spring Data Repositories.

你可以通过添加 -Xjsr305 编译器标志及其以下选项 -Xjsr305={strict|warn|ignore} 来配置 JSR-305 检查。

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 Data API 的考虑空安全的因素。从 Spring API 推断的 Kotlin 类型应该在了解 Spring API 空值声明可能会演变的知识下使用,即使在小版本之间也有可能,而且未来还有可能添加更多检查。

For Kotlin versions 1.1+, the default behavior is the same as -Xjsr305=warn. The strict value is required take Spring Data API null-safety into account. 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.