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?
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 operatormap[key] = value
), butMutableMap
does.On the JVM, the Kotlin
Map
andMutableMap
interfaces are both represented by thejava.util.Map
, so you can freely change your parameter type toMutableMap<String, String>
:Note that you might need to change
Map
toMutableMap
in some other places in your Kotlin code, as the compiler won't allow you to pass a read-onlyMap
as aMutableMap
argument.As for
HashMap
, given that it's a concrete implementation, it also implements theMutableMap
and therefore exposes the mutating functions. However, using interfaces and not implementation classes is more preferable.