我正在尝试编写一个 android Kotlin 应用程序,但出现以下错误。我哪里出错了?
这就是我声明我的 HashMap 的方式:
var mParent: MutableMap<*, *> ?= null
mParent = HashMap()
错误:
type inference failed. Not enough information to infer parameter K in constructor HashMap. Please specify it explicitly
最佳答案
您必须指定映射的键和值的类型。像这样的:
mParent = HashMap<String, String>()
或者像这样:
var mParent: MutableMap<String, String>? = null
mParent = HashMap()
使用 * 作为通用参数意味着任何类型的对象都可以作为键和值。因此,当您创建 HashMap 时,编译器不知道键和值的确切类型 - 它无法进行类型推断。这就是为什么你会得到这样的错误。
建议:Kotlin 习惯用法建议使用 mapOf()
或 mutableMapOf()
方法来创建 map ,而不是使用 Java 风格的 HashMap():
mParent = mutableMapOf<String, String>()
关于android - 错误 : type inference failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45519391/