Serializable in Kotlin

In my Android app, I had a TreeMap that I could happily add to the Bundle , for example

 bundle.putSerializable("myHappyKey", myHappyTreeMap); 

but now when I port my application to Kotlin, Android Studio complains that Serializable! is required Serializable! but instead he finds Map .

How can I handle this?

EDIT The warning seems to disappear if I drop the card on Serializable . Is it so?

EDIT 2 I declare and initialize myHappyTreeMap as

 var myHappyTreeMap: Map<Int, Double> = mapOf() 

The documentation says that maps initialized with mapOf() are serializable. If the documents say so ...

+6
source share
1 answer

TreeMap and various other Map implementations implement Serializable , but the Map interface itself does not extend Serializable .

I see several options:

  • Make sure that myHappyTreeMap not just a Map , but a TreeMap or some other Map subtype that extends / implements Serializable . eg:.

     val myHappyTreeMap: TreeMap = ... 
  • Copy your Map instance as Serializable (recommended only if you know the type of Map instance implements Serializable , otherwise you will get a ClassCastException ). eg:.

     bundle.putSerializable("myHappyKey", myHappyTreeMap as Serializable) 
  • Check your Map instance, and if it is not Serializable , then create a copy of it using the Map implementation. eg:.

     bundle.putSerializable("myHappyKey", when (myHappyTreeMap) { is Serializable -> myHappyTreeMap else -> LinkedHashMap(myHappyTreeMap) }) 
+5
source

Source: https://habr.com/ru/post/1013194/


All Articles