Kotlin 中的范围低于 API 21

Ranges in Kotlin below API 21

我想存储像 < 4.1, 29..35 > 这样的键值对,我可以用 HashMap<Double, Range<Int>>:

val womanMap: HashMap<Double, Range<Int>> = hashMapOf()

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun createMap() {
    //This both requires API 21
    val range = Range(29,35)
    womanMap[4.6] = Range.create(29,35)
} 

我如何在 API 21 级以下执行此操作?

Range is a class in the Android SDK, this is tied to API 21. You could use IntRange 由 Kotlin 标准库提供。

您可以找到 Kotlin 范围的用法示例 here

它们的基本用法如下:

val range = 1..10    // creation
println(range.first) // 1
println(range.last)  // 10
println(5 in range)  // true

改用IntRange

val womanMap: HashMap<Double, IntRange> = hashMapOf()

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun createMap() {
        val range = 29..35
        womanMap[4.6] = 29..35
    }

注意29..35是一个区间:

for (a in 29..35) print("$a ") // >>> 29 30 31 32 33 34 35

要创建不包含其结束元素的范围,请使用 29 until 35:

for (a in 29 until 35) print("$a ") // >>> 29 30 31 32 33 34

更多信息:Ranges