kotlincollectionsinitializationmutablemap

How to create a MutableMap with all keys initially set to same value in Kotlin?


I want to create a mutable map whose keys fall in a continuous range, and values initially set to the same value 9 in a single line using Kotlin. How to do that?


Solution

  • You can use the following way:

    import java.util.*
    
    fun main(args: Array<String>) {
    
        val a :Int = 0
        val b :Int = 7
        val myMap = mutableMapOf<IntRange, Int>()
        myMap[a..b] = 9
        myMap.toMap()
        println(myMap) //Output: {0..7=9}
    
    }