Extensions

Kotlin 扩展 为扩展现有类提供了额外的功能。Spring Framework Kotlin API 使用这些扩展来为现有的 Spring API 添加新的 Kotlin 特有便利。

Kotlin extensions provide the ability to extend existing classes with additional functionality. The Spring Framework Kotlin APIs use these extensions to add new Kotlin-specific conveniences to existing Spring APIs.

Spring Framework KDoc API 列出并记录了所有可用的 Kotlin 扩展和 DSL。

The Spring Framework KDoc API lists and documents all available Kotlin extensions and DSLs.

请记住,需要导入 Kotlin 扩展才能使用它们。这意味着,例如,GenericApplicationContext.registerBean Kotlin 扩展仅在导入 org.springframework.context.support.registerBean 时可用。也就是说,与静态导入类似,在大多数情况下,IDE 会自动建议导入。

Keep in mind that Kotlin extensions need to be imported to be used. This means, for example, that the GenericApplicationContext.registerBean Kotlin extension is available only if org.springframework.context.support.registerBean is imported. That said, similar to static imports, an IDE should automatically suggest the import in most cases.

例如,https://kotlinlang.org/docs/inline-functions.html#reified-type-parameters[Kotlin 具体类型参数] 为 JVM 泛型类型擦除 提供了解决方法,Spring Framework 提供了一些扩展来利用此特性。这允许获得更好的 Kotlin API RestTemplate,用于 Spring WebFlux 的新 WebClient,以及各种其他 API。

For example, Kotlin reified type parameters provide a workaround for JVM generics type erasure, and the Spring Framework provides some extensions to take advantage of this feature. This allows for a better Kotlin API RestTemplate, for the new WebClient from Spring WebFlux, and for various other APIs.

Reactor 和 Spring Data 等其他库也提供了适用于其 API 的 Kotlin 扩展,从而总体上提供了更好的 Kotlin 开发体验。

Other libraries, such as Reactor and Spring Data, also provide Kotlin extensions for their APIs, thus giving a better Kotlin development experience overall.

为了在 Java 中检索 User 对象的列表, 您通常会编写以下内容:

To retrieve a list of User objects in Java, you would normally write the following:

Flux<User> users  = client.get().retrieve().bodyToFlux(User.class)

使用 Kotlin 和 Spring 框架扩展, 您可以编写以下内容:

With Kotlin and the Spring Framework extensions, you can instead write the following:

val users = client.get().retrieve().bodyToFlux<User>()
// or (both are equivalent)
val users : Flux<User> = client.get().retrieve().bodyToFlux()

与在 Java 中一样, Kotlin 中的 users 是强类型, 但 Kotlin 巧妙的类型推断允许使用较短的语法。

As in Java, users in Kotlin is strongly typed, but Kotlin’s clever type inference allows for shorter syntax.