Calling "add" on List values of HashMap

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?

The List<T> interface represents a read-only list and doesn’t have add method.

1 Like

Right, I just found List - Kotlin Programming Language 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.