Hanbit the Developer

Kotlin Documentation | Ranges and progressions 본문

Mobile/Kotlin

Kotlin Documentation | Ranges and progressions

hanbikan 2023. 5. 24. 13:49

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

문서 링크: https://kotlinlang.org/docs/ranges.html


for (i in 1..4) print(i)
for (i in 4 downTo 1) print(i)
for (i in 1..8 step 2) print(i)
println()
for (i in 8 downTo 1 step 2) print(i)
for (i in 1 until 10) {       // i in 1 until 10, excluding 10
    print(i)
}
  • ..는 operator fun rangeTo()과 같다.
  • step, downTo는 infix fun이며, IntProgression 등을 반환한다.
  • until은 IntRange 등을 반환한다. 해당 클래스는 IntProgression을 확장하고 있다.

Progression

세 종류의 progression이 있다: IntProgression, LongProgression, CharProgression

progression은 세 프로퍼티를 가진다: first, last, step

이는 Java에서의 아래 코드와 같다.

for (int i = first; i <= last; i += step) {
  // ...
}

reversed()를 통해 뒤집을 수도 있다.

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

filter() 등 컬렉션 함수를 사용할 수도 있다.

println((1..10).filter { it % 2 == 0 })