I'm looking for some idiomatic Kotlin to replace a...
# getting-started
e
I'm looking for some idiomatic Kotlin to replace an element in a
List<T>
at some index, i.e. I'd create a new list. Currently I do:
Copy code
val list: List<T> = /*..*/
val elementToReplace: T = /*...*/
val newElement: T = /*..*/
val newList = list.toMutableList().apply {
    this[indexOf(elementToReplace)] = newElement
}
E.g. as an extension:
Copy code
fun <T> List<T>.replaceWith(old: T, new: T): List<T> = toMutableList().apply {
    this[indexOf(old)] = new
}
Can this be done with some stdlib function, or in a shorter more idiomatic way?
e
this is a bit different - it would replace any number of instances - but might work for you
Copy code
.map { if (it == old) new else it }
y
There's also
Copy code
.mapIndexed { index, element -> if(index == oldIndex) new else element }
Or, one of my favourite functions ever, `buildList`:
Copy code
newList = buildList(list.size) {
  addAll(list)
  this[indexOf(elementToReplace)] = newElement
}
(But this is very close to your
toMutableList
solution, except that
buildList
forces the list to be immutable afterwards.
e
Thanks, those are some really nice options!
What helps is that I know that all items are unique, so it could be a
Set<T>
, though a set is unordered and this actually models an ordered set, hence I use a
List<T>
.
🤔 Now that I think about it, should I use a
Set<T>
instead, and apply some sorting logic where the elements are consumed? Different question, but maybe you know something about this
y
What you're looking for is likely a TreeSet: https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
e
which can be obtained with
.toSortedSet()
in Kotlin, but depends on your usage patterns whether that is a good fit or not
e
Thanks again!
Ah, there's the catch. I use Kotlin JS (and eventually multiplatform) in this particular project, and there's no
SortedSet
in there 😅
But I can manage with my list of unique items
e
if you only need to consume the minimum element, you can implement a binary heap with a lot less effort than a binary or b tree
e
Oh, wait, I really meant ordered, not sorted. That's different 😉
e
`setOf`/`mutableSetOf` are documented to preserve insertion order. is that all you need?
e
Possibly... While
setOf
does preserve order, I believe that
Set<T>
in general means that there is no explicit / implied order. There likely is little reason to assume that the order in the set will change, but if the order isn't specified, then
Set<T>
isn't the correct interface to use