Kotlin Range

Kotlin Range

Kotlin은 λ²”μœ„λ₯Ό μ‰½κ²Œ 생성할 수 μžˆλŠ” rangeTo() ν•¨μˆ˜λ₯Ό μ œκ³΅ν•œλ‹€.
rangeTo()λŠ” .. μ˜€νΌλ ˆμ΄ν„°λ‘œ ν‘œν˜„λ„ κ°€λŠ₯ν•˜λ‹€.

val i = 1 
if (i in 1..4) { // equivalent of 1 <= i && i <= 4
    print(i)
}

/*
>> μ‹€ν–‰ κ²°κ³Ό
1
*/

IntRange, LongRange, CharRange λŠ” λ°˜λ³΅λ„ μ§€μ›ν•œλ‹€.

for (i in 1..4) print(i)

λ°˜λŒ€ μˆœμ„œλ‘œ λ°˜λ³΅ν•˜λ €λ©΄ .. λŒ€μ‹  downToλ₯Ό μ‚¬μš©ν•œλ‹€.

for (i in 4 downTo 1) print(i)

λ˜λŠ” 이미 정해진 μˆ˜μ—΄μ— reversed() ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•œλ‹€.

for (i in (1..4).reversed()) print(i)

step을 μ΄μš©ν•˜λ©΄ 1μ”© 증가/κ°μ†Œκ°€ μ•„λ‹Œ μ›ν•˜λŠ” 수만큼 κ±΄λ„ˆλ›Έ 수 μžˆλ‹€.

for (i in 1..8 step 2) print(i)
println()
for (i in 8 downTo 1 step 2) print(i)

λ§ˆμ§€λ§‰ μš”μ†Œλ₯Ό ν¬ν•¨ν•˜μ§€ μ•Šκ³  λ°˜λ³΅ν•˜λŠ” 경우, until을 μ‚¬μš©ν•œλ‹€.

for (i in 1 until 10) {  // i in [1, 10), 10은 ν¬ν•¨λ˜μ§€ μ•ŠμŒ
    print(i)
}

/*
>> μ‹€ν–‰ κ²°κ³Ό
1
2
(μƒλž΅)
9
*/

Comments