Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through array in Kotlin to replace elements

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading