Search code examples
kotlin

Kotlin Array Slice Indexing


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:])

Solution

  • 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