Morpheu5
Morpheu5

Reputation: 2801

Serializable in Kotlin

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…

Upvotes: 8

Views: 12304

Answers (1)

mfulton26
mfulton26

Reputation: 31224

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

I see some options:

  1. 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 = ...
    
  2. 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)
    
  3. 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)
    })
    

Upvotes: 8

Related Questions