Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializable in Kotlin

Tags:

android

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…

like image 972
Morpheu5 Avatar asked Dec 15 '16 15:12

Morpheu5


People also ask

What does serializable mean in Kotlin?

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.

Why is Kotlin serialized?

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.

Is Kotlin list serializable?

The simple data classes Pair and Triple from the Kotlin standard library are serializable.


1 Answers

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)
    })
    
like image 142
mfulton26 Avatar answered Oct 07 '22 12:10

mfulton26