Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Array Slice Indexing

Tags:

kotlin

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:])
like image 955
shinvu Avatar asked Dec 13 '25 12:12

shinvu


1 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

like image 188
orange-lotus Avatar answered Dec 16 '25 22:12

orange-lotus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!