Home > Blockchain >  Why does a nullable ArrayList give a Type Mismatch error when passing it a non-nullable ArrayList?
Why does a nullable ArrayList give a Type Mismatch error when passing it a non-nullable ArrayList?

Time:06-17

I am trying to pass a non-nullable ArrayList to a nullable ArrayList. But, it gives the type mismatch error: enter image description here

Now, ignoring this, if I try to run my program, I get this issue:

enter image description here

So, how can I make this work? I also tried to make my non-nullable array list to nullable but it does not seem to work.

CodePudding user response:

You can safe cast it like below

fun main() {
   val x: ArrayList<String> = ArrayList()
   test(x as ArrayList<String?>)
}

fun test(t: ArrayList<String?>) = println("worked")

CodePudding user response:

Both arrayLists are non-nullable, the difference is that the first one accepts a nullable QuestionOptionAdd and the second one accepts a non-nullable QuestionOptionAdd, okay let's explain why you get this error:

Let's say that we have two arrayLists the first one accepts String? and the second one accepts String:

val firstArrayList: ArrayList<String?> = arrayListOf("1", null, "3", "4", null)
val secondArrayList: ArrayList<String> = arrayListOf("1", "2", "3", "4", "5")

Okay now let's try to change the first element of each array, we can change element from firstArrayList to null, but that's not the case for secondArrayList :

firstArrayList[0] = null
secondArrayList[0] = "0"

So when you move the elements of secondArrayList to firstArrayList, it causes that problem because secondArrayList elements can't be nullable and firstArrayList elements must be nullable.

So the solution for this problem is to clear firstArrayList and add to it all the elements of secondArrayList:

firstArrayList.clear()
firstArrayList.addAll(secondArrayList)
  • Related