Passing a Map from Java to Kotlin does not compile when updating the map

2.4k views Asked by At

I have a Java function that has a Map<String, String and needs to pass it to a Kotlin function for adding values to the map.
The problem is that if I have:

fun updateMap(map: Map<String, String>)

It seems that the map is immutable and I can't do: map[KEY] = VALUE as I get compilation error.
It would work if I did: fun updateMap(map: HashMap<String, String>) but in that case I can't pass the original map from the Java code without some casting which I would like to avoid if possible.
What is the solution for this?

1

There are 1 answers

2
hotkey On BEST ANSWER

Kotlin, unlike Java, has separate interfaces for mutable and read-only collections, see Kotlin Collections Overview.

The Map interface in Kotlin doesn't expose any modifying functions (including the operator map[key] = value), but MutableMap does.

On the JVM, the Kotlin Map and MutableMap interfaces are both represented by the java.util.Map, so you can freely change your parameter type to MutableMap<String, String>:

fun updateMap(map: MutableMap<String, String>) {
    map["foo"] = "bar"
}

Note that you might need to change Map to MutableMap in some other places in your Kotlin code, as the compiler won't allow you to pass a read-only Map as a MutableMap argument.

As for HashMap, given that it's a concrete implementation, it also implements the MutableMap and therefore exposes the mutating functions. However, using interfaces and not implementation classes is more preferable.