rangeTo所在位置是kotlin.ranges.rangeTo,其相关用法介绍如下。

用法一

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

创建从该 Comparable 值到指定 that 值的范围。

该值需要小于或等于that值,否则返回范围为空。

例子:

import java.sql.Date
import kotlin.test.assertFalse
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val start = Date.valueOf("2017-01-01")
val end = Date.valueOf("2017-12-31")
val range = start..end
println(range) // 2017-01-01..2017-12-31

println("Date.valueOf(\"2017-05-27\") in range is ${Date.valueOf("2017-05-27") in range}") // true
println("Date.valueOf(\"2018-01-01\") in range is ${Date.valueOf("2018-01-01") in range}") // false
println("Date.valueOf(\"2018-01-01\") !in range is ${Date.valueOf("2018-01-01") !in range}") // true
//sampleEnd
}

输出:

2017-01-01..2017-12-31
Date.valueOf("2017-05-27") in range is true
Date.valueOf("2018-01-01") in range is false
Date.valueOf("2018-01-01") !in range is true

用法二

operator fun Double.rangeTo(
    that: Double
): ClosedFloatingPointRange<Double>

创建从该 Double 值到指定 that 值的范围。

根据 IEEE-754 将数字与该范围的末端进行比较。

例子:

import java.sql.Date
import kotlin.test.assertFalse
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val range = 1.0..100.0
println(range) // 1.0..100.0

println("3.14 in range is ${3.14 in range}") // true
println("100.1 in range is ${100.1 in range}") // false
//sampleEnd
}

输出:

1.0..100.0
3.14 in range is true
100.1 in range is false

用法三

operator fun Float.rangeTo(
    that: Float
): ClosedFloatingPointRange<Float>

创建从该 Float 值到指定 that 值的范围。

根据 IEEE-754 将数字与该范围的末端进行比较。

例子:

import java.sql.Date
import kotlin.test.assertFalse
import kotlin.test.assertTrue

fun main(args: Array<String>) {
//sampleStart
val range = 1f..100f
println(range) // 1.0..100.0

println("3.14f in range is ${3.14f in range}") // true
println("100.1f in range is ${100.1f in range}") // false
//sampleEnd
}

输出:

1.0..100.0
3.14f in range is true
100.1f in range is false