I want to create a mutable map whose keys are initially set to the same value 9 in a single line using Kotlin. How to do that?
CodePudding user response:
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}
}
CodePudding user response:
If you mean values, you can use the withDefault
function on any Map / MutableMap:
fun main() {
val map = mutableMapOf<String, Int>().withDefault { 9 }
map["hello"] = 5
println(map.getValue("hello"))
println(map.getValue("test"))
}