Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Kotlin Array<T> implement Iterable<T>

Why doesn't the Array<T> class in Kotlin implement Iterable<T>?

A quick look at the documentation reveals that it already has an iterator() method too.

like image 912
Eric Avatar asked Mar 11 '16 11:03

Eric


People also ask

Is array iterable Kotlin?

Java arrays don't implement Iterable , so Kotlin arrays (which are virtually the same) do not as well. We could make our arrays implement Iterable by creating a standalone class which does not relate to Java arrays.

Do arrays implement Iterable?

Iterable objects are a generalization of arrays. That's a concept that allows us to make any object useable in a for..of loop. Of course, Arrays are iterable.

What is the key difference between iterable T and sequence T in Kotlin?

The order of operations execution is different as well: Sequence performs all the processing steps one-by-one for every single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.

Why array is not a collection in Kotlin?

Arrays are a lower level object type so they don't implement any interface. This is due to compatibility with the JVM. In Java, Array isn't a class. It would just not work.


1 Answers

Kotlin is designed to be fully interoperable with Java. Array<X> is X[] both at runtime and from Java's point of view. Java arrays don't implement Iterable, so Kotlin arrays (which are virtually the same) do not as well.

We could make our arrays implement Iterable by creating a standalone class which does not relate to Java arrays. However, in order to maintain compatibility with Java, we'd have to perform implicit conversions from such type to Java arrays and back. Implicit conversions are generally not the perfect approach because of performance overhead and unclear object identity semantics. Here they would also solve only a half of the problem, since you'd still have to manually "box" arrays when calling Kotlin code from Java. This is why such solution was not considered as feasible.

like image 150
Alexander Udalov Avatar answered Sep 21 '22 13:09

Alexander Udalov