AVEbrahimi
AVEbrahimi

Reputation: 19144

Kotlin forEach order

Does Kotlin forEach iterate through an array in real order of array or it may be sometimes in another order? I mean does this always print 1,2,3,...9 or it may print something like this 1,5,3,4,...

val numbers: Array<Int> = array(1,2,3,4,5,6,7,8,9)
    numbers.forEach({(number: Int) ->
        Log.d(tag,number)
    })

Kotlin forEach reference

Upvotes: 3

Views: 6785

Answers (3)

tweitzel
tweitzel

Reputation: 353

These are two separate questions. Yes, as pointed out by the other answers, it keeps the order. But since forEach doesn't print anything, it all depends on the implementation of the printing.

For example, this will not always print the numbers 1 to 10 in order, even though it uses forEach:

fun myPrint(i: Int) = launch { println(i) }

(1..10).forEach { n -> myPrint(n) }

Since we don't know how your Log.d(...) is implemented, we can't be sure.

Upvotes: 2

Arseniy
Arseniy

Reputation: 688

Yeah, it keeps real order. Look at implementation:

public inline fun IntArray.forEach(action: (Int) -> Unit): Unit {
        for (element in this) action(element)
    }

For loop uses iterator of the array, which keeps order too.

Upvotes: 3

triad
triad

Reputation: 21507

forEach iterates in order from first to last element; source code:

Collections.kt

/**
 * Performs the given [action] on each element.
 */
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

Upvotes: 7

Related Questions