Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Kotlin MutableMap to java.util.HashMap

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.

like image 860
Fadel Trivandi Dipantara Avatar asked Aug 27 '18 10:08

Fadel Trivandi Dipantara


People also ask

What is mutablemap in Kotlin and how to use it?

Kotlin MutableMap is an interface of collection framework that holds the object in the form of key and value pair. The values of MutableMap interface are retrieved by using their corresponding keys. The key and value may be of different pairs such as <Int, Int>,<Int, String>, <Char, String> etc. Each key of MutableMap holds only one value.

How to map to list in Kotlin?

Use toList () method on map object or keys, values properties. 5. Kotlin Map to List using entries properties map.entries properties will returns the key-value pairs. Use map () method on the entries object. We can use the any pattern in between the key and value.

How to convert LinkedHashMap to list in Kotlin?

Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor From the above program, the output is not in the order what is inserted into the map. To preserve the insertion order then need to use LinkedHashMap class instead of HashMap.

What is the difference between map and mutablemap in Java?

The map is invariant in its key type. V - the type of map values. The mutable map is invariant in its value type. Represents a key/value pair held by a MutableMap. Returns a MutableSet of all key/value pairs in this map. Returns a MutableSet of all keys in this map. Returns a MutableCollection of all values in this map.


2 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)
like image 110
Akaki Kapanadze Avatar answered Sep 19 '22 09:09

Akaki Kapanadze


You can use hashMapOf instead.

product.params = hashMapOf<String, Any?>(
    "name" to response.name,
    "type" to response.type
)
like image 21
EpicPandaForce Avatar answered Sep 23 '22 09:09

EpicPandaForce