# 区间

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

``````fun main() {
//sampleStart
for (i in 1..4) print(i)
//sampleEnd
}``````

``````fun main() {
//sampleStart
for (i in 4 downTo 1) print(i)
//sampleEnd
}``````

``````fun main() {
//sampleStart
for (i in 1..4 step 2) print(i)

for (i in 4 downTo 1 step 2) print(i)
//sampleEnd
}``````

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

## 它是如何工作的

`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] 的数列``````