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

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

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

有一个函数返回一个哈希映射,但与MutableList的值

  fun getDataStatus(response: JSONObject?): HashMap<String, MutableList> { return HashMap<String, MutableList>() } 

当将结果传递给期望列表的HashMap时,会出现错误:

  mMap = getDataStatus(resp) //<== got error 

有错误:

 Error:(81, 35) Type mismatch: inferred type is HashMap<String, MutableList> but HashMap<String, List>? was expected 

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

投它

考虑到MutableListList一个子类,你可以投它。 这里只有一个问题:你将失去永恒性。 如果将ListMutableList ,则可以修改其内容。

 mMap = getDataStatus(repo) as HashMap> 

转换它

为了保持列表的不变性,你必须将每个MutableList转换为一个不可变的List

 mMap = HashMap>() getDataStatus(repo).forEach { (s, list) -> mMap?.put(s, list.toList()) } 

在这种情况下,如果您尝试修改mMap中的列表内容,将会抛出exception。

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

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

要么

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

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

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

一个好的解决方案是:

 private var mMap: Map>? = 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> if you really need //HashMap interface 

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

 val mMap = mutableMapOf() 

或立即:

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