본문 바로가기
코틀린/[Elements] 요소 작업

[Kotlin][Collection] forEach / forEachIndexed

by jinwo_o 2024. 8. 9.

각 요소에 대해 지정된 작업을 수행합니다.

public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit): Unit {
    for (element in this) operation(element)
}


val list = listOf(1, 2, 3, 4)
list.forEach { num -> print(num) } // 1234

 

각 요소에 대해 지정된 작업을 수행하여 요소에 순차적 인덱스를 제공합니다.

public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T) -> Unit): Unit {
    var index = 0
    for (item in this) action(checkIndexOverflow(index++), item)
}


"Hello".forEachIndexed { i, v: Char -> print("$i$v ") } // 0H 1e 2l 3l 4o

 

forEach - Kotlin Programming Language

 

kotlinlang.org

 

forEachIndexed - Kotlin Programming Language

 

kotlinlang.org