在kotlin中,如何传递一个MutableList,其中目标需要一个List

有一个定义为List值的哈希映射:

private var mMap: HashMap<String, List<DataStatus>>? = null 

有一个函数返回一个哈希映射,但与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一个子类,你可以投它。 这里只有一个问题:你将失去永恒性。 如果将ListMutableList ,则可以修改其内容。

 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中的列表内容,将会抛出异常。

如果您不打算在返回给您之后将新项目放入地图中,则只需声明您的变量具有更宽松的类型即可:

 // prohibits calling members that take List<DataStatus> as a parameter, // so you can store a HashMap with values of any List subtype, // for example of MutableList private var mMap: HashMap<String, out List<DataStatus>>? = null 

要么

 // prohibits calling mutating methods // List<DataStatus> already has 'out' variance private var mMap: Map<String, List<DataStatus>>? = null 

如果由于某种原因需要该变量具有该类型,则需要在返回的映射中转换或上传值:

 mMap = getDataStatus(resp).mapValuesTo(HashMap()) { (_, v) -> v as List<DataStatus> } 

一个好的解决方案是:

 private var mMap: Map<String, List<DataStatus>>? = null // Do you //really need to have object with interface of HashMap? I don't think so.. mMap = getDataStatus(resp).mapValues { it.value.toList() } // add as HashMap<String, List<DataStatus>> if you really need //HashMap interface 

因此,在使用Kotlin时,不推荐使用var +可空类型。 也许你想要如下:

 val mMap = mutableMapOf<String, List<DataStatus>() 

或立即:

 val mMap = getDataStatus(resp).mapValues { it.value.toList() }