๋ฐ์ํ
์ฝํ๋ฆฐ์ ์ฒ์ ์ฌ์ฉํ์ ๋, ์๋ฐ์๋ ์กฐ๊ธ ๋ค๋ฅด๊ฒ for๋ฌธ์ ํตํด ๋ฐ๋ณต๋ฌธ์ ์์ฑํ์๊ธฐ์ ์กฐ๊ธ ์ด์ํ์๋๋ฐ์,
์๋ฐ์์์ for๋ฌธ์ ๋๋ถ๋ถ(?) for, for-each ๋ ๋ฐฉ์์ ์ฌ์ฉํด์ ์ ๊ทผํ๋๋ฐ, ์ฝํ๋ฆฐ์์๋ ๊ต์ฅํ ๋ค์ํ ๋ฐฉ์์ผ๋ก Array์ ์ ๊ทผ์ด ๊ฐ๋ฅํด์ ๋์ฑ ์ด์ํ๋ ๊ฒ ๊ฐ์ต๋๋ค.
ํจ์ํ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด์ for๋ฌธ์ ์ฌ์ฉํ ์ผ์ด ๋ง์ง๋ ์์ง๋ง, ๊ฐ๋ตํ๊ฒ ์ ๋ฆฌํด๋ณด๊ณ ์ ํฉ๋๋ค.
https://kotlinlang.org/docs/iterators.html#mutable-iterators
// 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)
๊ต์ฅํ ๋ง์ ๊ฒ ๊ฐ์๋๋ฐ, ๊ทธ๋ ๊ฒ ๋ง์ง๋ ์๋ค์.. ๐
๋ฐ์ํ
'Kotlin' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Kotlin - Scope functions (let, with, run, apply, also) (0) | 2024.12.15 |
---|---|
[Kotlin] Slack API๋ก ์ฌ๋ ์ฑ๋์ Message ๋ฐ์กํ๊ธฐ (3) | 2022.03.27 |
[Kotlin] - Class(ํด๋์ค) (0) | 2021.10.17 |
๋๊ธ