I have two lists in Kotlin, of the same size, foodObjects: MutableList<ParseObject>?
and checked: MutableList<Boolean>?
. I need to do a for
loop and get the objectId
from foodObjects
every time that an element of checked
is true. So it is this in Java:
for (int i = 0; i < foodObjects.size(); i++) {
// here
}
But in Kotlin, I don't know why, there are some problems. In fact, if I do this:
for (i in 0..foodObjects!!.size) {
if (checked?.get(i) == true) {
objectsId?.add(foodObjects.get(i).objectId)
}
}
I've got IndexOutOfBoundsException
. I don't know why, it continues the loop also at foodObjects.size
. I could do it also with filter
and map
:
(0..foodObjects!!.size)
.filter { checked?.get(it) == true }
.forEach { objectsId?.add(foodObjects.get(it).objectId) }
but I'm getting the same error. I use this to stop the error and get it to work:
for (i in 0..foodObjects!!.size) {
if (i < foodObjects.size) {
if (checked?.get(i) == true) {
objectsId?.add(foodObjects.get(i).objectId)
}
}
}
Everyone could tell me why in Kotlin I need to do it, when in Java it works good?