In my Android app, I had a TreeMap that I could happily put in a Bundle like
bundle.putSerializable("myHappyKey", myHappyTreeMap);
but now that I'm porting my app to Kotlin, Android Studio complains that Serializable! is required, but it's finding a Map instead.
How do I deal with this?
EDIT The warning seems to vanish if I cast my map to a Serializable. Is this the way?
EDIT 2 I am declaring and initialising myHappyTreeMap as
var myHappyTreeMap: Map<Int, Double> = mapOf()
The documentation says that maps initialised using mapOf() are serializable. If the docs says so…
The Kotlin Serialization library generates serializers for classes annotated with @Serializable . A serializer is a class that handles an object's serialization and deserialization. For every class annotated with @Serializable , the compiler generates a serializer on its companion object.
Kotlin serialization consists of a compiler plugin, that generates visitor code for serializable classes, runtime library with core serialization API and support libraries with various serialization formats. Supports Kotlin classes marked as @Serializable and standard collections.
The simple data classes Pair and Triple from the Kotlin standard library are serializable.
TreeMap and various other Map implementations implement Serializable but the Map interface itself does not implement Serializable.
I see some options:
Make sure the type of myHappyTreeMap is not simply Map but TreeMap or some other Map subtype that implements Serializable. e.g.:
val myHappyTreeMap: TreeMap = ...
Cast your Map instance as Serializable (only recommended if you know the Map instance type implements Serializable otherwise you will get a ClassCastException). e.g.:
bundle.putSerializable("myHappyKey", myHappyTreeMap as Serializable)
Check your Map instance and if it isn't Serializable then make a copy of it using a Map implementation that is. e.g.:
bundle.putSerializable("myHappyKey", when (myHappyTreeMap) {
is Serializable -> myHappyTreeMap
else -> LinkedHashMap(myHappyTreeMap)
})
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