拥有一个以 List 作为值定义的 hashMap:
private var mMap: HashMap<String, List<DataStatus>>? = null
有一个函数返回一个 hashMap 但具有 MutableList 的值
fun getDataStatus(response: JSONObject?): HashMap<String, MutableList<DataStatus>> {
return HashMap<String, MutableList<AccountStatusAlert>>()
}
将结果传递给期望 List 的 hashMap 时出现错误:
mMap = getDataStatus(resp) //<== got error
出现错误:
Error:(81, 35) Type mismatch: inferred type is HashMap<String,
MutableList<DataStatus>> but HashMap<String, List<DataStatus>>? was expected
最佳答案
根据您的需要,您有两种解决方案。
转换它
考虑到 MutableList
是 List
的子类,您可以强制转换它。这里只有一个问题:您将失去不变性。如果将 List
转换回 MutableList
,则可以修改其内容。
mMap = getDataStatus(repo) as HashMap<String, List<String>>
转换它
为了保持列表的不变性,你必须将每个MutableList
转换成一个不可变的List
:
mMap = HashMap<String, List<String>>()
getDataStatus(repo).forEach { (s, list) ->
mMap?.put(s, list.toList())
}
在这种情况下,如果你试图在mMap
中修改列表的内容,将会抛出异常。
关于android - 在 kotlin 中,如何在目标需要 List 的地方传回 MutableList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46650079/