๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Kotlin

Kotlin for iterator

by ์ฃผ๋ฐœ2 2025. 1. 17.
๋ฐ˜์‘ํ˜•

์ฝ”ํ‹€๋ฆฐ์„ ์ฒ˜์Œ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ, ์ž๋ฐ”์™€๋Š” ์กฐ๊ธˆ ๋‹ค๋ฅด๊ฒŒ for๋ฌธ์„ ํ†ตํ•ด ๋ฐ˜๋ณต๋ฌธ์„ ์ž‘์„ฑํ–ˆ์—ˆ๊ธฐ์— ์กฐ๊ธˆ ์–ด์ƒ‰ํ–ˆ์—ˆ๋Š”๋ฐ์š”,

์ž๋ฐ”์—์„œ์˜ for๋ฌธ์€ ๋Œ€๋ถ€๋ถ„(?) for, for-each ๋‘ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ด์„œ ์ ‘๊ทผํ–ˆ๋Š”๋ฐ, ์ฝ”ํ‹€๋ฆฐ์—์„œ๋Š” ๊ต‰์žฅํžˆ ๋‹ค์–‘ํ•œ ๋ฐฉ์‹์œผ๋กœ Array์— ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•ด์„œ ๋”์šฑ ์–ด์ƒ‰ํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

ํ•จ์ˆ˜ํ˜• ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด์„œ for๋ฌธ์„ ์‚ฌ์šฉํ•  ์ผ์ด ๋งŽ์ง€๋Š” ์•Š์ง€๋งŒ, ๊ฐ„๋žตํ•˜๊ฒŒ ์ •๋ฆฌํ•ด๋ณด๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

 

https://kotlinlang.org/docs/iterators.html#mutable-iterators

 

Iterators | Kotlin

 

kotlinlang.org

 

 

// 12345
for (i in 1..5) {
    print(i)
}


// 1234
for (i in 1..<5) {
    print(i)
}


// 1234
for (i in 1 until 5) {
    print(i) // 1234
}


// ์ถœ๋ ฅ X
for (i in 5..1) {
    print(i) // ์ถœ๋ ฅ X
}


// 54321
for (i in 5 downTo 1) {
    print(i) // 54321
}


// 1 4 7 10
for (i in 1..10 step 3) {
    print("$i ") // 1 4 7 10
}


// 12345
sequenceOf(1, 2, 3, 4, 5).forEach(::print)

 

.. (Primitives.kt)

 

until (_Ranges.kt)

 

downTo (_Ranges.kt)

 

step (_Ranges.kt)

 

 

val numbers = listOf(1, 2, 3, 4)


// 1234
for (number in numbers) {
    print(number)
}


// 1234
numbers.forEach(::print)


// 1234
numbers.forEach { print(it) }


// [0] 1
// [1] 2
// [2] 3
// [3] 4
numbers.forEachIndexed { index, i -> println("[$index] $i") }



// [0] 1
// [1] 2
// [2] 3
// [3] 4
for (i in numbers.indices) {
    val number = numbers[i]
    println("[$i] $number")
}



// [0] 1
// [1] 2
// [2] 3
// [3] 4
for ((i, number) in numbers.withIndex()) {
    println("[$i] $number")
}


// 01234
repeat(5) { i ->
    print("$i")
}

 

 

forEach (_Collections.kt)

 

forEachIndexed (_Collections.kt)

 

indices (Collections.kt)

 

withIndex (_Collections.kt)

 

repeat (Standard.kt)

 

sequenceOf (Sequences.kt)

_Arrays.kt ํด๋ž˜์Šค .... 24,000์ค„;;;

 

 

๊ต‰์žฅํžˆ ๋งŽ์„ ๊ฒƒ ๊ฐ™์•˜๋Š”๋ฐ, ๊ทธ๋ ‡๊ฒŒ ๋งŽ์ง€๋Š” ์•Š๋„ค์š”.. ๐Ÿ˜‚

 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€