在Kotlin中,如何在目的地需要列表的地方传递回MutableList [英] in kotlin, how to pass back a MutableList where the destination expects a List

查看:1036
本文介绍了在Kotlin中,如何在目的地需要列表的地方传递回MutableList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有定义了List作为值的hashMap:

having a hashMap with List as value defined:

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

具有一个函数返回一个hashMap,但其值为MutableList

having a function return a hashMap but with the value of MutableList

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

          return HashMap<String, MutableList<AccountStatusAlert>>()
     }

将结果传递给hashMap期望列表时,出现错误:

when pass the result to the hashMap expecting List it got error:

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

得到错误:

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

推荐答案

您有两种解决方案,具体取决于您的需求.

You have two solutions depending on your needs.

发布

考虑到MutableListList的子类,可以对其进行强制转换.这里只有一个问题:您将失去不变性.如果将List投射回MutableList,则可以修改其内容.

Considering that MutableList is a subclass of List, you can cast it. There's only a problem here: you will lose immutability. If you cast the List back to MutableList, you can modify its content.

mMap = getDataStatus(repo) as HashMap<String, List<String>>

转换

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

In order to maintain immutability on the list, you have to convert each MutableList to an immutable List:

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

在这种情况下,如果您尝试修改mMap中列表的内容,则会引发异常.

In this case, if you try to modify the content of a list inside mMap, an exception will be thrown.

这篇关于在Kotlin中,如何在目的地需要列表的地方传递回MutableList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆