Calling "add" on List values of HashMap


#1

Quick question: Why does

    val map = HashMap<String, ArrayList<String>>().withDefault { arrayListOf() }
    map["foo"]!!.add("bar")

compile fine, but

    val map = HashMap<String, List<String>>().withDefault { arrayListOf() }
    map["foo"]!!.add("bar")

does not? The only difference is ArrayList vs List in the HashMap declaration. As the List interface has “add”, why can’t I call it and get a compiler error instead?


#2

The List<T> interface represents a read-only list and doesn’t have add method.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/


#3

Right, I just found https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html myself saying

A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

A bit confusing coming from Java, I have to say.