From 63770fb07483fba5a32f9a6c5123ab82bdbce6c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Deleuze?= Date: Mon, 9 Oct 2023 12:38:23 +0200 Subject: [PATCH] Document Kotlin declaration-site variance subtleties Closes gh-31370 --- .../languages/kotlin/spring-projects-in.adoc | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc b/framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc index 021d436a37..3fcc9d51a6 100644 --- a/framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc +++ b/framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc @@ -236,6 +236,42 @@ be matched, not only the `GET` method. +[[declaration-site-variance]] +== Declaration-site variance + +Dealing with generic types in Spring applications written in Kotlin may require, for some use cases, to understand +Kotlin https://kotlinlang.org/docs/generics.html#declaration-site-variance[declaration-site variance] +which allows to define the variance when declaring a type, which is not possible in Java which supports only use-site +variance. + +For example, declaring `List` in Kotlin is conceptually equivalent to `java.util.List` because +`kotlin.collections.List` is declared as +https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/[`interface List : kotlin.collections.Collection`]. + +This needs to be taken in account by using the `out` Kotlin keyword on generic types when using Java classes, +for example when writing a `org.springframework.core.convert.converter.Converter` from a Kotlin type to a Java type. + +[source,kotlin,indent=0] +---- +class ListOfFooConverter : Converter, CustomJavaList> { + // ... +} +---- + +When converting any kind of objects, star projection with `*` can be used instead of `out Any`. +[source,kotlin,indent=0] +---- +class ListOfAnyConverter : Converter, CustomJavaList<*>> { + // ... +} +---- + +NOTE: Spring Framework does not leverage yet declaration-site variance type information for injecting beans, +subscribe to https://github.com/spring-projects/spring-framework/issues/22313[spring-framework#22313] to track related +progresses. + + + [[testing]] == Testing