2

I created a WeakHashMap in Kotlin and for some reason, I am unable to call put it, it won't resolve.

val dataMap: Map<Int, MyData> = WeakHashMap<Int, MyData>()
dataMap.put(myInt, myData) // doesn't resolve

Is there a Kotlin equivalent for a WeakHashMap?

VIN
  • 6,385
  • 7
  • 38
  • 77

3 Answers3

7

You have cast your WeakHashMap to a read-only Map, so you have restricted it to not have a put function. You should make the variable type MutableMap or leave it as a WeakHashMap.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
1

Thanks @Tenfour04. Removing the type of the dataMap resolved the issue (no longer programmed to interface but made to be of type WeakHashMap.

val dataMap = WeakHashMap<Int, MyData>()
styleDataMap.put(myInt, myData)
VIN
  • 6,385
  • 7
  • 38
  • 77
  • 1
    You could still program to the interface by using the type `MutableMap<…>` (which has the `put()` method) instead of `Map<…>` (which doesn't). – gidds Jan 20 '21 at 23:11
0

The put is defined in WeakHashMap but not directly in Map itself. Values of a Map are read-only hence it prevents using any put method there. you can either use reference of WeakHashMap or you can convert to a MutableMap to call put

  val styleDataMap: WeakHashMap<Int, MyData> = WeakHashMap<Int, MyData>()
  styleDataMap.put(myInt, myData)

or

  val styleDataMap: Map<Int, MyData> = WeakHashMap<Int, MyData>()
  styleDataMap.toMutableMap().put(myInt, myData) // doesn't resolve
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • styleDataMap.toMutableMap() is not a good solution, because at every call it will create a new mutable map object – Dmitry Jan 21 '21 at 14:21