Iterating over Arrays and Lists

We'll cover the following

You can seamlessly use any of the JDK collection classes and interfaces in Kotlin. Thus, you can use Java’s array and java.util.List in Kotlin as well. Creating instances of these in Kotlin is simpler than in Java, and you can iterate over the values in these collections with greater ease in Kotlin.

Iterate with values

Let’s first create an array of numbers and examine its type:

// iterate.kts
val array = arrayOf(1, 2, 3)

println(array.javaClass) //class [Ljava.lang.Integer;

To create an array of values, use the arrayOf() function that belongs to the kotlin package. The functions that belong to the kotlin package may be called without the kotlin prefix—kotlin.arrayOf(), for example—or without any explicit imports.

Since all the values given are of type Int, the array created in this example is an array of Integer values. To create a primitive int array, instead of an array of Integer objects, use the intArrayOf() function. Irrespective of which function we pick, we can iterate over the array of values using the for(x in ...) syntax like before.

// iterate.kts
for (e in array) { print("$e, ") } //1, 2, 3,

Likewise, you can create an instance of List<T> using the listOf() function and then iterate over its values using for:

Get hands-on with 1200+ tech skills courses.