2017-08-05 137 views
-2

我想寫一個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

回答

1

你必須指定類型的地圖的關鍵和價值。事情是這樣的:

mParent = HashMap<String, String>() 

或者這樣:

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

有*的泛型參數意味着,任何類型的對象允許作爲鍵和值。所以當你創建HashMap時,編譯器不知道鍵和值的確切類型 - 它不能輸入推論。這就是爲什麼你會得到這樣的錯誤。

建議:科特林成語建議使用mapOf()mutableMapOf()方法來創建地圖,而不是使用Java風格的HashMap():

mParent = mutableMapOf<String, String>() 
0

可以在科特林使用HashMap中像這樣的....

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

如果您不確定您的密鑰和值是什麼,那麼請使用Any

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

在你的情況下,編譯器不確定這些aestriks是什麼意思。