2

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?

TapanHP
  • 5,969
  • 6
  • 37
  • 66

2 Answers2

5

Range is a class in the Android SDK, this is tied to API 21. You could use IntRange provided by the Kotlin standard library instead though.

You can find usage examples for Kotlin ranges here.

Here's what their basic usage looks like:

val range = 1..10    // creation
println(range.first) // 1
println(range.last)  // 10
println(5 in range)  // true
zsmb13
  • 85,752
  • 11
  • 221
  • 226
4

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

Alex Romanov
  • 11,453
  • 6
  • 48
  • 51