Best way to "replace" an element of an immutable list

Not sure if it’s a douche move to revive this topic – if so, then I apologize – but in the interest of helping anyone still looking for a solution to this issue, I’ll give it a go:

My take on this was a function that took a new value and a lambda, and returned a new list where the elements for which the lambda returned true were replaced:

fun <T> List<T>.replace(newValue: T, block: (T) -> Boolean): List<T> {
  return map {
    if (block(it)) newValue else it
  }
}

On replacing 1 with 99 in the sample:

val list = listOf(1, 2, 3)
val updatedList = list.replace(newValue = 99) { it == 1 }

This would of course replace every insteance of 1, but could also be complemented with a similar replaceFirst or replaceLast function as well.

Hope this helps anyone looking for a similar solution!

9 Likes