I am trying to copy one ArrayList
to another ArrayList
in Kotlin
1st ArrayList
:
private var leadList1: ArrayList<Lead> = ArrayList()
2nd ArrayList
:
val leadList2: ArrayList<Lead?>?
I tried to use addAll()
. leadList1.addAll(leadList2)
But its not working.
Error showing:
Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?
This isn't safe to do, because your first list can only contain objects of type Lead
, while your second one has Lead?
as its type parameter, meaning that it might contain null
values. You can't add those to the first list.
The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:
private var leadList1: ArrayList<Lead?> = ArrayList()
Or you can add only the non-null elements of the second list to the first one:
leadList1.addAll(leadList2.filterNotNull())
And in either case, you'll have to perform a null check on leadList2
, because the entire list itself is marked as potentially null as well, signified by the last ?
of the type ArrayList<Lead?>?
.
if (leadList2 != null) {
leadList1.addAll(leadList2.filterNotNull())
}
You can simply pass another List instance into the constructor of your new List
val originalList = arrayListOf(1,2,3,4,5)
val orginalListCopy = ArrayList(originalList)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With