Android kotlin Object Any type mismatch

Multi tool use
Android kotlin Object Any type mismatch
How to assign kotlin map to java library map.
This gives type mismatch error for Object and Any.
I need to assign java map variable in a 3rd party java library, from my kotlin code map.
val model = JavaModel() //from 3rd party java library
val params:MutableMap<String, Any> = HashMap()
params.put("key","value")
model.params = params //gives error below
Type mismatch: inferred type is MutableMap<String, Any>
but Map<String, Object>?
was expected
MutableMap<String, Any>
Map<String, Object>?
What is "java library map"? Where is your code?
– f1sh
Jul 3 at 7:51
Show the code for your
JavaModel
class, in particular the params
field declaration.– Leo Aso
Jul 3 at 7:58
JavaModel
params
İt is compiled code I am not able to see it. Only thing that I can say is JavaModel.params is Map<String, Object>
– DiRiNoiD
Jul 3 at 8:00
3 Answers
3
Java's Object
is not the same as Kotlin's Any
, so the type MutableMap<String, Any>
and Map<String, Object>?
mismatched, because you cannot change the 3rd party java library, just declare the params
as:
Object
Any
MutableMap<String, Any>
Map<String, Object>?
params
val params: MutableMap<String, Object> = HashMap()
Kotlin will show Type mismatch for such code:
var param: MutableMap<String, Object?> = hashMapOf(); param.put("key", "")
– 3mpty
Jul 3 at 8:26
var param: MutableMap<String, Object?> = hashMapOf(); param.put("key", "")
Your are right 3mpty, so what is the solution? Both solution gives exact same error.
– DiRiNoiD
Jul 3 at 8:37
Seems right, @DiRiNoiD you should share more info about your
JavaModel
– Hong Duan
Jul 3 at 9:27
JavaModel
JavaModel.params
requires explicitly <String, Object>
. You cannot use Kotlin Any
there. Also HashMap
in Kotlin is mapped type so your best shot is to do simple workaround:
JavaModel.params
<String, Object>
Any
HashMap
Extend HashMap from java, ex. ParamsMap.java
:
ParamsMap.java
public class ParamsMap extends HashMap<String, Object> { }
And use it like this:
val model = JavaModel()
val params = ParamsMap()
params.put("key","value")
model.params = params
The only thing I can achieve this is to create a new Java class and do the operation inside it. I give the params Java Map as parameter and and I made the operation inside the Java class.
Kotlin automatically behaves any Object as Any so it gives type mismatch for the assignment.
public class ObjectMapper {
public static void setParam(Map<String, Object> params, String key, String value) {
params.put(key, value);
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
post your code.
– Brijesh Joshi
Jul 3 at 7:51