Home > Software design >  on Kotlin exists other way to set array data?
on Kotlin exists other way to set array data?

Time:12-01

I would like to know if it is the optimal way to set values on a array

fun setParameters(myArray: MutableList<Symbol>, instance: MutationData){ 

    myArray.forEachIndexed { index, valArr ->
            myArray[index] = setValues(valArr, members?.settings)
            myArray[index] = setValueForByReference(instance, myArray[index])
        }
}

or if exist a better way as create another array and fill into and after return the new array I don't know what do you think?

learn if I did right with this solution or get a optimal way to solve

CodePudding user response:

You can use mapIndexed

myArray.mapIndexed { index, valArr ->
        setValues(valArr, members?.settings)
        setValueForByReference(instance, myArray[index])
    }

CodePudding user response:

Whether you need to create a copy or not depends on all the surrounding code and how the array is used. It is actually somewhat rare in practice to use arrays at all. You should default to using List unless you are working in code that needs to be highly optimized or you need something that is mutable but with fixed size.

Your current code modifies the existing array. If this is what you need, it could be simplified slightly by avoiding the array write and extra array read with the intermediate value:

myArray.forEachIndexed { index, valArr ->
    val interimValue = setValues(valArr, members?.settings)
    myArray[index] = setValueForByReference(instance, interimValue)
}

If you don't need to modify the array, so a copy is OK, you can use the map function. But it returns a List, not an Array. Like I said above, you usually should prefer working with Lists anyway. map makes this a bit easier because you don't have to deal with the index.

val newList = myArray.map { valArr ->
    val interimValue = setValues(valArr, members?.settings)
    setValueForByReference(instance, interimValue)
}

Edit based on your update and comment:

forEachIndexed() is already quite optimized. I would maybe pull out the ?.settings property call so you aren't doing it repeatedly:

val settings = members?.settings
myArray.forEachIndexed { index, valArr ->
    val interimValue = setValues(valArr, settings)
    myArray[index] = setValueForByReference(instance, interimValue)
}
  • Related