其他分享
首页 > 其他分享> > android – Kotlin合并两个可空的可变列表

android – Kotlin合并两个可空的可变列表

作者:互联网

val mutableList1: MutableList<TeamInvitationData?>?
val mutableList2: MutableList<TeamInvitationData?>?

addAll方法可以用于合并可空的可变列表但是,这里它会抛出编译时错误.

例:

val map1 = listOne?.map { TeamInvitationData(it) }
val map2 = listTwo?.map { TeamInvitationData(it) }
map1.addAll(map2)

Type interface failed ,Please try to specify type argument explicitly.

在这里,任何方式我可以合并这两个数组,提前谢谢.

解决方法:

这里有几个解决方案.

>如果您需要将所有元素添加到mutableList1:

val mutableList1: MutableList<Any?>? = ...
val mutableList2: MutableList<Any?>? = ...

mutableList1?.let { list1 -> mutableList2?.let(list1::addAll) }

>如果您需要新的可空列表作为结果:

val mutableList1: MutableList<Any?>? = ...
val mutableList2: MutableList<Any?>? = ...

val list3: List<Any?>? = mutableList1?.let { list1 ->
    mutableList2?.let { list2 -> list1 + list2 }
}

>如果您需要新的可空可变列表作为结果:

val mutableList1: MutableList<Any?>? = ...
val mutableList2: MutableList<Any?>? = ...

val list3: MutableList<Any?>? = mutableList1
        ?.let { list1 -> mutableList2?.let { list2 -> list1 + list2 } }
        ?.toMutableList()

>如果您需要新的非空列表作为结果:

val mutableList1: MutableList<Any?>? = ...
val mutableList2: MutableList<Any?>? = ...

val list3: List<Any?> = mutableList1.orEmpty() + mutableList2.orEmpty()

标签:android,kotlin,rx-kotlin
来源: https://codeday.me/bug/20190823/1698001.html