The answer given by @hluhovskyi is a good one, but there is one more posibility from his second option, where you need new nullable list as result:
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 } }
In this exmaple, in case mutableList1 is empty, you will have automatically and empty list ignoring if the mutableList2 has elements.
So, if you need the sum of the two lists and need a nullable list only if the two lists are null, you will need to do:
val mutableList1: MutableList<Any?>? = ...
val mutableList2: MutableList<Any?>? = ...
val list3: List<Any?>? = mutableList1?.let { list1 ->
mutableList2?.let { list2 -> list1 + list2 }
?: list1
} ?: mutableList2
So, now you will have as result:
- Null list if both were null at the begining
- The sum of both list if both were not null
- In case one is null and the other have elemnts, it will return the list with elements.
addAll
. You don't show any line of code that would need type inference, either. – Carthusianmap1
andmap2
to beMutableList
becauselistOne
andlistTwo
are mutable, butmap
actually returns an immutableList
and so you can't calladdAll
on it. While your question is about merging mutable lists, your code doesn't attempt that. – Carthusian