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 ?
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
In general, you cannot typecast a Map to a HashMap without risk of a class-cast exception. If the Map is a TreeMap then the cast will (and must) fail. You can avoid the exception by making using instanceof to check the type before you cast, but if the test says "not a HashMap" you are stuck.
The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
Use the set() method to add a key/value pair to a Map , e.g. map. set('myKey', 'myValue') . The set() method adds or updates the element with the provided key and value and returns the Map object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With