Home » Java » Convert Kotlin MutableMap to java.util.HashMap

Convert Kotlin MutableMap to java.util.HashMap

Posted by: admin December 28, 2021 Leave a comment

Questions:

I am working with a pretty old project that has a lot of java code in it, and to replace it, it will be too much of a hassle, and as kotlin is much better than java, I’m trying to coed all the new code in kotlin, but when I try to access a java code with this kotlin code

val params = mutableMapOf<String, String>(
    "name" to response.name,
    "type" to response.type
)
product.params = params

I got a red underline below the params, it said

Required: Hashmap<String!, Any!>!
Found: MutableMap<String, String>

This is my java setter

public void setParams(HashMap<String, Object> params){
    this.params = params;
}

Can I fix this without changing the java code? Please help if it is possible, or if it is not, and what is the workaround to fix this.

Answers:

You can construct a new HashMap from the params:

val params = mutableMapOf<String, String>(
    "name" to response.name,
    "type" to response.type
)
product.params = HashMap(params)

###

You can use hashMapOf instead.

product.params = hashMapOf<String, Any?>(
    "name" to response.name,
    "type" to response.type
)

###

You need to use HashMap<> istead mutableMapOf()

    val params = HashMap<String, String>()
    params.put("name", response.name)
    params.put("type", response.type)
    product.params = params