Kotlin Array Slice Indexing

Viewed 6087

Let's say I want to iterate through all but the first element in Kotlin IntArray. Currently, I'm doing it like this:

fun minimalExample(nums: IntArray): Unit {
    for(num in nums.sliceArray(IntRange(1,nums.size-1))) println(num)
}

Is there an easy syntax for doing this like in Python (I don't want to have to specify the ending index of the nums array):

for (num in nums[1:])
3 Answers

I think you could use Kotlin's drop which will remove the first n elements of an array.

fun minimalExampleWithDrop(nums: IntArray): Unit {
    for(num in nums.drop(1)) println(num)
}

minimalExampleWithDrop(intArrayOf(1,2,3,4,5,6))
// 2
// 3
// 4
// 5
// 6

Repl.it: https://repl.it/repls/SvelteShadyLivecd

A basic for loop with 1 as starting index

    val myList = intArrayOf(1,2,3,4,5,6)

    for(i in 1 until myList.size){
        Log.d(TAG,"${myList[i]}")
    }

Or since it's an IntArray you can use it as an Iterator and skip elements like shown here

    val iterator = myList.iterator()
    // skip an element
    if (iterator.hasNext()) {
        iterator.next()
    }
    iterator.forEach {
        Log.d(TAG,"it -> $it")
    }

You can alternatively also use the slice method which is present in lists and arrays. Here are examples for both:

val a = listOf(1, 2, 3, 4)
println(a.slice(1..a.size - 1))

val b = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
println(b.slice(4..5))

This will print out:

[2, 3, 4]
[5, 6]
Related