2
votes

I am trying to write an android Kotlin application but I got below error. Where have I gone wrong ?

This is how I have declared my HashMap:

 var mParent: MutableMap<*, *> ?= null
 mParent = HashMap()

Error:

type inference failed. Not enough information to infer parameter K in constructor HashMap. Please specify it explicitly

3

3 Answers

7
votes

You have to specify the types of the key and value of the map. Something like this:

mParent = HashMap<String, String>()

Or like this:

var mParent: MutableMap<String, String>? = null
mParent = HashMap()

Having * as the generic parameter means, any type of object allowed as the key and value. So when you create the HashMap, the compiler has no idea what the exact type of the key and value - it cannot type infer. That's why you get an error like that.

Suggestion: Kotlin idiom suggests to use the mapOf() or mutableMapOf() method to create a map rather than using the Java style HashMap():

mParent = mutableMapOf<String, String>()
1
votes

You can use HashMap like this in kotlin....

val context = HashMap<String, Any>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
1
votes

If you are not sure what are your keys and values are going to be then use Any.

var mParent: MutableMap<Any, Any> ?= mutableMapOf()

In your case compiler is not sure what those aestriks means.