Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: type inference failed

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

like image 933
Nyagaka Enock Avatar asked Jun 01 '26 20:06

Nyagaka Enock


2 Answers

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>()
like image 143
Bob Avatar answered Jun 03 '26 08:06

Bob


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)
like image 33
Vishal Vaishnav Avatar answered Jun 03 '26 10:06

Vishal Vaishnav