https://kotlinlang.org logo
#announcements
Title
# announcements
e

evkaky

07/10/2017, 1:14 PM
guys, I need to iterate over some collection but not from first index, and I don’t want to deal with indices at all. I know, in python there is an
enumerate(arr, fromId)
built-in function for that purpose:
Copy code
for elem in enumerate(arr, 2): // elem = arr[2], arr[3] ... arr[n-1]
Is there something like that in kotlin std lib?
g

gjesse

07/10/2017, 1:54 PM
evkaky: you could write an extension function that does this for you if there isn’t one
Copy code
kotlin

fun <T> Iterable<T>.enumerate(startIdx: Int): Iterable<T> {
    return this.filterIndexed { index, t -> index >= startIdx }
}
then you can do
Copy code
listOf(0,1,2,3,4)
            .enumerate(2)
            .forEach {
                println(it)
            }
or you could just use filterIndexed directly 🙂
m

marstran

07/10/2017, 2:28 PM
You can use
for (n in arr.drop(2)) { .. ]
9 Views