Search code examples
kotlinkotlin-null-safety

In Kotlin, what is the idiomatic way to deal conditional way to initialize complex map


Recently I find myself dealing with maps of <String, List<...>> like this:

val bc = mutableMapOf<String, MutableSet<Int>>()
if (bc[question] == null)
  bc[question] = mutableSetOf()
bc[question]!!.add(line)

Isn't there a better way to do this? I've tried

bc[question]?.add(x) ?: = mutableSetOf(x)

But that won't work. I've looked here and on the Kotlin null-safety page and other similar questions here but didn't find anything. I'm still some-what new to Kotlin.


Solution

  • I do it using run function to assign mutableSetOf you can try it

     bc[question]?.add(line) ?: run { bc[question] = mutableSetOf(line) }