Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Volley Kotlin: (Mutable)Map<(raw) Any?, (raw) Any?>! vs MutableMap<String, String>

In Android with Kotlin and Volley Library, I am using the below code to put a map into jsonObject.

val params = mutableMapOf<String, String>()
params["key1"] = "value1"
params["key2"] = "value2"
val parameter = JSONObject(params)

This give me the below error:

Java type mismatch expected (Mutable)Map<(raw) Any?, (raw) Any?>! but found MutableMap<String, String>. Use explicit cast
  1. Why do I need explicit cast as params as Map<*, *>
  2. What is (Mutable)Map?
  3. What are differences between (Mutable)Map and MutableMap?
like image 229
Yunus Karakaya Avatar asked May 11 '26 17:05

Yunus Karakaya


1 Answers

The JSONObject constructor takes a Map with raw types (the generics are not specified). As such you should supply a map that can be of Any type :

val params = mutableMapOf<Any?, Any?>()
    params["key1"] = "value1"
    params["key2"] = "value2"
    val parameter = JSONObject(params)

The warning (Mutable)Map<(raw) Any?, (raw) Any?> is showing the Java parameter argument - stating it can expect either a Map or MutableMap, as you are calling Java code from Kotlin - Java won't know if the Map is mutable or immutable. Just to note raw types are not supported by Kotlin, you only encounter this problem if calling Java code.

like image 116
Mark Avatar answered May 14 '26 08:05

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!