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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With