I'm learning Kotlin and I want to iterate through array to replace some elements.
To change something inside elements I do this:
if (arr != null){ // Kotlin doesn't like NullReferenceException
for(elem in arr) { // for each element
elem.property ; // do something with element
}
}
But when I want to replace element at some position I have to do this:
if (arr != null){ // Kotlin doesn't like NullReferenceException
if (arr.size > 0) { // check size
for (i in 0..arr.size - 1) { // for all elements
if (i == 5){ // if something
arr[i] = buildNewElement(); // replace element
}
}
}
}
This is a bit ugly.
Does Kotlin offer something nicer or something that could reduce lines of code?
CodePudding user response:
So first of all, because you are using kotlin you should rarely need to do a if (someVal != null)
check. Nullable types have a safe call operator that you can use instead: ?.
If the requirement is to keep the array in place, consider using forEachIndexed (with the usual caveats about modifying an array in-place):
arr?.forEachIndexed { i, value ->
arr[i] = buildNewElement()
}
If you don't need to use value, you can rename it to _
If you do not need to do this in-place and can generate a new array, you should instead consider map