# Kotlin區間/範圍

``````if (i in 1..10) { // 等同於 1 <= i && i <= 10
println(i)
}``````

``````for (i in 1..4) print(i) // 輸出「1234」

for (i in 4..1) print(i) // 什麼都不輸出``````

``for (i in 4 downTo 1) print(i) // 輸出「4321」``

``````for (i in 1..4 step 2) print(i) // 輸出「13」

for (i in 4 downTo 1 step 2) print(i) // 輸出「42」``````

``````for (i in 1 until 10) {   // i in [1, 10) 排除了 10
println(i)
}``````

## 它是如何工作的

`ClosedRange<T>` 在數學意義上表示一個閉區間，它是爲可比較類型定義的。

`Progression` 迭代相當於 Java/JavaScript 的基於索引的 for{: .keyword }-循環：

``````for (int i = first; i != last; i += step) {
// ……
}``````

`downTo()``step()` 函數的結果總是一個 `*Progression`

``IntProgression.fromClosedRange(start, end, step)``

## 一些實用函數

### `rangeTo()`

``````class Int {
//……
operator fun rangeTo(other: Long): LongRange = LongRange(this, other)
//……
operator fun rangeTo(other: Int): IntRange = IntRange(this, other)
//……
}``````

``    public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T>``

### `downTo()`

``````fun Long.downTo(other: Int): LongProgression {
return LongProgression.fromClosedRange(this, other.toLong(), -1L)
}

fun Byte.downTo(other: Int): IntProgression {
return IntProgression.fromClosedRange(this.toInt(), other, -1)
}``````

### `reversed()`

``````fun IntProgression.reversed(): IntProgression {
return IntProgression.fromClosedRange(last, first, -step)
}``````

### `step()`

``````fun IntProgression.step(step: Int): IntProgression {
if (step <= 0) throw IllegalArgumentException("Step must be positive, was: \$step")
return IntProgression.fromClosedRange(first, last, if (this.step > 0) step else -step)
}

fun CharProgression.step(step: Int): CharProgression {
if (step <= 0) throw IllegalArgumentException("Step must be positive, was: \$step")
return CharProgression.fromClosedRange(first, last, if (this.step > 0) step else -step)
}``````

``````(1..12 step 2).last == 11  // 值爲 [1, 3, 5, 7, 9, 11] 的數列
(1..12 step 3).last == 10  // 值爲 [1, 4, 7, 10] 的數列
(1..12 step 4).last == 9   // 值爲 [1, 5, 9] 的數列``````