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 ?
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.
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.
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)
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