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
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>()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With