Johann
Johann

Reputation: 29867

A forEach function that supports stepping

In Kotlin, I want to iterate through a list of items in steps of 2. This would be done like this:

for (i in 0..users.lastIndex step 2) {
   val user = users[i]
}

This is okay, but it would be nicer if there was something even simpler like a forEach. But a forEach doesn't provide stepping. Is there an API that does allow you to provide stepping in a forEach fashion? Something like this:

users.forEach(step = 2) { user ->
   
}

Upvotes: 0

Views: 1222

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23091

Using forEach to replace a for loop is against the Kotlin coding conventions, which also comes with a reminder to keep performance considerations in mind when chaining higher-order functions. Worth keeping in mind before you start going crazy with extension functions :-)

Prefer using higher-order functions (filter, map etc.) to loops. Exception: forEach (prefer using a regular for loop instead, unless the receiver of forEach is nullable or forEach is used as part of a longer call chain).

When making a choice between a complex expression using multiple higher-order functions and a loop, understand the cost of the operations being performed in each case and keep performance considerations in mind.

Upvotes: 3

Slaw
Slaw

Reputation: 45806

As far as I know there's no such function in the Kotlin standard library. However, it's not too difficult to create your own extension function:

inline fun <T> List<T>.forEachStep(step: Int = 1, action: (T) -> Unit) {
    /*
     * May want to have an iterator-based solution as well for lists that
     * don't support random access. You could choose which solution to
     * use based on 'if (this is RandomAccess)'.
     */
    for (i in indices step step) {
        action(get(i))
    }
}

Which you can then use on any List.

val users: List<User> = ...
users.forEachStep(step = 2) { user ->
    // do something...
}

Upvotes: 4

Related Questions