2

I was using bundle.getSerializable("data") as HashMap<Int, Int>

but after changing sdkVersion to 33 .getSerializable() API is updated.

I am unable to implement it for HashMap<Int, Int>

I tried -

savedInstanceState.getSerializable("answer", HashMap<Int, Int>::class.java)!!

but it gives warning -

Only classes are allowed on the left hand side of a class literal

After some searching I found this stack post

The respective answer(above cited) quote -

You can't use generics with class

Now I am not getting the solution of this problem. Any suggestion?

codegsaini
  • 87
  • 6

1 Answers1

3

You should use HashMap::class.java and cast it to HashMap<Int, Int>.

val map = HashMap<Int, Int>()
map[1] = 123

val bundle  = Bundle()
bundle.putSerializable("answer", map)

val serializedMap = bundle.getSerializable("answer", HashMap::class.java) as HashMap<Int, Int>
println(serializedMap[1])
ocos
  • 1,901
  • 1
  • 10
  • 12
  • Also works the same way for `ArrayList<>`, just put ArrayList.class as the third argument in the new `getSerializable` function and cast the result as `ArrayList`. – Petr Krýže Feb 01 '23 at 15:31