1

The question came up when I took a closer look at kotlin .map inline function. Here's its definition

public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R>{
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)}

In the function definition, it should return a List, which is defined in Collection.kt. However, it is returning an ArrayList, which implements a List interface in Java (List.java)

What is the relationship between Java interface and Kotlin interface ? I imagine there would be more similar examples, maybe Set, or Map?

Yao
  • 709
  • 2
  • 11
  • 22

1 Answers1

4

On the JVM platform, the Kotlin interface kotlin.collections.List is mapped to Java interface java.util.List, and so is kotlin.collections.MutableList.

It means that the usages of these Kotlin interfaces are compiled to usages of the Java List interface in the bytecode. On the other hand, the Java List interface usages in the signatures read from the libraries are seen as kotlin.collections.(Mutable)List.

There are more mapped types: see the reference.

This allows for calling Kotlin from Java and vice versa in a seamless way while still representing the Java types as kotlin.* classes in Kotlin, which, for example, saves us from primitives and arrays not being classes, and introduces immutability through interfaces.

hotkey
  • 140,743
  • 39
  • 371
  • 326