j2emanue
j2emanue

Reputation: 62519

Kotlin - how to make a map serializable

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 ?

Upvotes: 9

Views: 10963

Answers (1)

Jitendra A
Jitendra A

Reputation: 1658

Use HashMap in place of MutableMap.

The bundle requires a Serializable object. MutableMap is an interface and hence is not serializable. 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)

Upvotes: 14

Related Questions