How do I call "put" on a WeakHashMap in Kotlin?

705 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

1
On

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
1
On

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)