Home > Mobile >  Null safety in Kotlin for MutableMap with MutableList
Null safety in Kotlin for MutableMap with MutableList

Time:07-09

I am trying to run this example

fun main() {
    val mlist: MutableList<String> = mutableListOf<String>()
    val mapp: MutableMap<Int, MutableList<String>> = mutableMapOf(1 to mlist)
    println(mapp)
    mapp[1].add("a") // Correct is mapp[1]?.add("a")
    println(mapp)
}

at Online Kotlin Compiler.

The compiler is complaining about Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type MutableList<String>?.

Although I have defined MutableList<String> why the compiler says something about MutableList<String>?.

What does the compiler understand more than me?! What am I missing here?

CodePudding user response:

The compiler does not say: '... something about MutableList<String>?.' What the compiler is saying, is, that mapp[1] could return null.

 mapp[1]       // this is the short notation for:
 mapp.get(1)   

Both return in your case a MutableList<String>?. Why is this return value nullable? It could be that mapp does not contain an element with the key 1. And then get(1) will return null.

If you are absolutely sure, that the element with key 1 is present in mapp use !!, if not use ? and add("a") will not be executed.

CodePudding user response:

in mutableMap, value can be added or removed, the compiler has no guarantee that the value is still present or has been changed before accessing the value in mutableMap types

  • Related