gpt4 book ai didi

android - 在 kotlin 中,如何在目标需要 List 的地方传回 MutableList

转载 作者:IT老高 更新时间:2023-10-28 13:47:28 24 4
gpt4 key购买 nike

拥有一个以 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

最佳答案

根据您的需要,您有两种解决方案。

转换它

考虑到 MutableListList 的子类,您可以强制转换它。这里只有一个问题:您将失去不变性。如果将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com