Erik
09/19/2022, 10:02 AMList<T>
at some index, i.e. I'd create a new list.
Currently I do:
val list: List<T> = /*..*/
val elementToReplace: T = /*...*/
val newElement: T = /*..*/
val newList = list.toMutableList().apply {
this[indexOf(elementToReplace)] = newElement
}
E.g. as an extension:
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?ephemient
09/19/2022, 10:09 AM.map { if (it == old) new else it }
Youssef Shoaib [MOD]
09/19/2022, 10:29 AM.mapIndexed { index, element -> if(index == oldIndex) new else element }
Youssef Shoaib [MOD]
09/19/2022, 10:33 AMnewList = 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.Erik
09/19/2022, 12:36 PMErik
09/19/2022, 12:38 PMSet<T>
, though a set is unordered and this actually models an ordered set, hence I use a List<T>
.Erik
09/19/2022, 12:40 PMSet<T>
instead, and apply some sorting logic where the elements are consumed? Different question, but maybe you know something about thisYoussef Shoaib [MOD]
09/19/2022, 12:59 PMephemient
09/19/2022, 1:03 PM.toSortedSet()
in Kotlin, but depends on your usage patterns whether that is a good fit or notErik
09/19/2022, 1:57 PMErik
09/19/2022, 2:47 PMSortedSet
in there 😅Erik
09/19/2022, 2:49 PMephemient
09/19/2022, 4:02 PMErik
09/19/2022, 4:39 PMephemient
09/20/2022, 2:41 AMErik
09/20/2022, 7:55 AMsetOf
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