I want to update element in a list, but since list doesn't have update method so I want to do something like this.
val dogs = listOf("shiba", "golden", "samoid")
// update if dog is shiba, otherwise remain the same value.
dogs.map { dog ->
if(dog == "shiba") { "doge" }
else { dog }
}
It works but ugly and I don't like it. I have seen other people create an extension function and it's so cool.
fun <T> MutableList<T>.mapInPlace(mutator: (T) -> (T)) {
this.forEachIndexed { i, value ->
val changedValue = mutator(value)
if (value != changedValue) {
this[i] = changedValue
}
}
}
// now I can use
dogs.mapInPlace { xxx }
I wan to have my own update method how can I do that. I expect something liek this
dogs.update { dog -> dog == "shiba" } { "doge" }