Why Java ArrayList is compatible with the Kotlins List interface

Why does it work

val foo: kotlin.collections.List<String> = java.util.ArrayList() 

ArrayList does not inherit the Kotlin List , is it?

+5
source share
2 answers

This is because kotlin.collections.List among other types, is a mapped type : at compile time for the JVM, its use is compiled into the corresponding Java interface applications java.util.List .

+4
source

The reason for this is because the Kotlin compiler will map the Java platform type (e.g. java.util.ArrayList() ) to the platform-independent Kotlin platform ( kotlin.collections.List ). Unsurprisingly, therefore they are called Mapped Types .

The key to understanding is that after compilation you only need binary compatibility. If all Kotlin code on the java platform uses the java.util.List interface when using the kotlin.collections.List object, stack manipulations on the java engine work just fine. The same is true in the opposite direction.

As for the other direction: as this question indicates, at least on the Java platform, kotlin.collections.ArrayList is essentially typealias for java.util.ArrayList .

+3
source

Source: https://habr.com/ru/post/1276026/


All Articles