Error: type inference failed

12,469

Solution 1

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>()

Solution 2

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.

Solution 3

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)
Share:
12,469
Nyagaka Enock
Author by

Nyagaka Enock

Enock: A very calm and collected person who prefers keeping his emotions hidden. Able to forgive others very easily. Determind and always thinking ahead. A very cool guy to those who know me. I am basically a happy person. I find solace and contentment in simple things. I know what I want. I don't need to be 'cool'. I don't go with the flow. I don't do things against my principles. I am brave enough to be ME. You can't make me anyless myself. My life is not a bore, unless I'm not happy with it anymore Writing Code is my Joy of Living

Updated on June 09, 2022

Comments

  • Nyagaka Enock
    Nyagaka Enock about 2 years

    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