Skip to content

Commit 63770fb

Browse files
committed
Document Kotlin declaration-site variance subtleties
Closes gh-31370
1 parent 9df4bce commit 63770fb

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

framework-docs/modules/ROOT/pages/languages/kotlin/spring-projects-in.adoc

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,42 @@ be matched, not only the `GET` method.
236236

237237

238238

239+
[[declaration-site-variance]]
240+
== Declaration-site variance
241+
242+
Dealing with generic types in Spring applications written in Kotlin may require, for some use cases, to understand
243+
Kotlin https://kotlinlang.org/docs/generics.html#declaration-site-variance[declaration-site variance]
244+
which allows to define the variance when declaring a type, which is not possible in Java which supports only use-site
245+
variance.
246+
247+
For example, declaring `List<Foo>` in Kotlin is conceptually equivalent to `java.util.List<? extends Foo>` because
248+
`kotlin.collections.List` is declared as
249+
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/[`interface List<out E> : kotlin.collections.Collection<E>`].
250+
251+
This needs to be taken in account by using the `out` Kotlin keyword on generic types when using Java classes,
252+
for example when writing a `org.springframework.core.convert.converter.Converter` from a Kotlin type to a Java type.
253+
254+
[source,kotlin,indent=0]
255+
----
256+
class ListOfFooConverter : Converter<List<Foo>, CustomJavaList<out Foo>> {
257+
// ...
258+
}
259+
----
260+
261+
When converting any kind of objects, star projection with `*` can be used instead of `out Any`.
262+
[source,kotlin,indent=0]
263+
----
264+
class ListOfAnyConverter : Converter<List<*>, CustomJavaList<*>> {
265+
// ...
266+
}
267+
----
268+
269+
NOTE: Spring Framework does not leverage yet declaration-site variance type information for injecting beans,
270+
subscribe to https://github.com/spring-projects/spring-framework/issues/22313[spring-framework#22313] to track related
271+
progresses.
272+
273+
274+
239275
[[testing]]
240276
== Testing
241277

0 commit comments

Comments
 (0)