I have these code segments. I want to find the optimal solution and if it's possible some explanation why my 1st piece of code is broken. I have struggled with adding elements to the existing Array<>, without minimal external stuff. I tried with +=' '.plus(), and.plusElement(), and the only solution I found to work is by coping the current array to MutableList and then adding an element to it. After that, I convert it again to Array and return the right type Array<>. I am sure that there is a more elegant way, but I can't brainstorm it.
Question 2: I also tried to shorten the code with with(), let{} run{}, etc. to make program.description.data.options as it. or this. instead of creation of new var clone
Thank you in advance :)
I have some nested data classes for Serialization in Kotlin
*FavouriteProgramCommandString have property val description: FavouriteProgram
->
FavouriteProgram have val data: FavouriteProgramDetails
-> FavouriteProgramDetails have var options: Array<FavouriteProgramOptions>,
*
data class FavouriteProgramDetails(
@SerializedName(value = "key", alternate = ["featureKey"])
val key: String,
@SerializedName("options")
var options: Array<FavouriteProgramOptions>,
)
Broken code:
@JvmStatic
fun getProgramDescriptionOfFavouritesWithDelayOption(
program: FavouriteProgramCommandString,
key: String,
delayDuration: Double = 0.0,
): FavouriteProgram {
with(program.description.data.options) {
val nodeOption =
firstOrNull { it.key == key }
if (nodeOption != null) {
this[this.indexOf(nodeOption)].value = delayDuration
} else {
this.plus(FavouriteProgramOptions(key, delayDuration)) // DONT'WORK
}
}
return program.description // Absolutly the same array is returned.
}
Working code:
@JvmStatic
fun getProgramDescriptionOfFavouritesWithDelayOptio2n(
program: FavouriteProgramCommandString,
key: String,
delayDuration: Double = 0.0,
): FavouriteProgram {
val clone = program.description.data.options.toMutableList()
val nodeOption =
clone.firstOrNull { it.key == key }
if (nodeOption != null) {
val index = clone.indexOf(nodeOption)
clone[index].value = delayDuration
} else {
clone.add(FavouriteProgramOptions(key, delayDuration)) // It's working.
}
program.description.data.options = clone.toTypedArray()
return program.description // Return what is expected.
}
Arrayand not aList(or mutable list)? The whole purpose of an array is that it is a fixed size sequential memory region. YourFavouriteProgramOptionsobject is obviously not a primitive as well, so there isn't even that optimisation to gain.plus()is an operator function that appends the element to a NEW collection, and returns the result. It does NOT change the initial list provided. kotlinlang.org/docs/collection-plus-minus.html