'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



Solution 1:[1]

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:

val params: MutableMap<String, Object> = HashMap()

Solution 2:[2]

JavaModel.paramsrequires 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:

Extend HashMap from java, ex. 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

Solution 3:[3]

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);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hong Duan
Solution 2 3mpty
Solution 3 DiRiNoiD