Kotlin merge two nullable mutable list

QuokMoon picture QuokMoon · Jan 12, 2018 · Viewed 18.3k times · Source
val mutableList1: MutableList<TeamInvitationData?>?
val mutableList2: MutableList<TeamInvitationData?>?

addAll method can be use to merge nullable mutable list but, here it throws me compile time error.

Example:

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.

Here Any way can I merge this two array , thanks in advance.

Answer

hluhovskyi picture hluhovskyi · Jan 12, 2018

Here are couple of solutions.

  1. In case if you need to add all elements to mutableList1:

    val mutableList1: MutableList<Any?>? = ...
    val mutableList2: MutableList<Any?>? = ...
    
    mutableList1?.let { list1 -> mutableList2?.let(list1::addAll) }
    
  2. In case if you need new nullable list as result:

    val mutableList1: MutableList<Any?>? = ...
    val mutableList2: MutableList<Any?>? = ...
    
    val list3: List<Any?>? = mutableList1?.let { list1 ->
        mutableList2?.let { list2 -> list1 + list2 }
    }
    
  3. In case if you need new nullable mutable list as result:

    val mutableList1: MutableList<Any?>? = ...
    val mutableList2: MutableList<Any?>? = ...
    
    val list3: MutableList<Any?>? = mutableList1
            ?.let { list1 -> mutableList2?.let { list2 -> list1 + list2 } }
            ?.toMutableList()
    
  4. In case if you need new non-null list as result:

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