Putting element into HashMap with Map interface
11,523
In the first example map gets the type of HashMap, in the second example you cast it to the Interface Map.
Map is a readonly map, there is no put/set, see here
In order to be able to edit the map, you should use MutableMap
Related videos on Youtube
Author by
ashur
Updated on September 14, 2022Comments
-
ashur over 1 year
I'm trying Kotlin and I've encountered a small problem that I can't resolve. When I have the following construction I can put elements into the map:
val map = HashMap<String, String>() map["asd"] = "s" map.put("34", "354")
However when I create a map with the
Map
interface I can only read them, what I'm doing wrong ?val map: Map<String, String> = HashMap<String, String>(); map.put("24", "34") //error map["23"] = "23" //error
Or maybe I'm confusing something about interfaces in Kotlin ?
-
Big Kahuna almost 7 yearsComing from Java, it's important to remember that Map is not coming from java.util.Map but from Map defined in Collections.kt. As a Kotlin newbie, I've been caught out by this as well. As mentioned above Map is readonly; to change the map use MutableMap. There's also helper methods to create different maps in Maps.kt i.e. hashMapOf etc