Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - how to make a map serializable

Tags:

kotlin

I am programming in android (but for this question it might not matter). i have a kotlin map defined as follows:

var filters: MutableMap<String, Any?>

i need to pass it to another screen (Activity in android) and for this i ususally make it serializable in java. but in kotlin this data structure is not serializable. Lets see what i am trying to do:

var b = Bundle()
b.putSerializable("myFilter",filters) //- this gives a compile error that filters is not serializable. 

I tried calling filters.toMap() but that does not work either. How is this done in kotlin ? how can i send a map to another screen in android ?

like image 843
j2emanue Avatar asked Aug 23 '18 16:08

j2emanue


People also ask

How do you make a map object serializable?

We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program.

How make Kotlin immutable map?

mapOf — creating an immutable map The first and most standard way of creating a map in Kotlin is by using mapOf . mapOf creates an immutable map of the key-value pairs we provide as parameters. Since the map is immutable, we won't find methods like put , remove or any other modifying functions.


1 Answers

Use HashMap in place of MutableMap.

The bundle requires a Serialiable object. MutableMap is an interface and hence is not serialiable. HashMap is a concrete class which implements serializable. You can use any concrete sub class of Map which implements serializable

Create a hashmap :

val filters: HashMap<String, Any?> = HashMap()
filters.put("a", 2)

Or

val filters: HashMap<String, Any?> = hashMapOf("a" to 2)

Put into bundle:

val b = Bundle()
b.putSerializable("myFilter", filters)
like image 177
Jitendra A Avatar answered Dec 31 '22 20:12

Jitendra A