Search code examples
androidkotlinandroid-api-levels

Ranges in Kotlin below API 21


I want to store key-value pairs like < 4.1, 29..35 > which I can do with a 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)
} 

How can I do this below API level 21?


Solution

  • Use IntRange instead:

    val womanMap: HashMap<Double, IntRange> = hashMapOf()
    
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        fun createMap() {
            val range = 29..35
            womanMap[4.6] = 29..35
        }
    

    Note that 29..35 is a closed interval:

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

    To create a range which does not include its end element use 29 until 35:

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

    For more info: Ranges