dave08
04/07/2021, 9:11 AMdata class Foo(val id: Int, val name: String)
What's an ideomatic way of searching for an id
and replacing in-place the entry with another name (without turning the list into a map)? And return the id or the found entry as a bonus..Big Chungus
04/07/2021, 9:14 AMdave08
04/07/2021, 9:15 AMarekolek
04/07/2021, 9:15 AMdave08
04/07/2021, 9:15 AMBig Chungus
04/07/2021, 9:16 AMdave08
04/07/2021, 9:17 AMarekolek
04/07/2021, 9:18 AMAnd return the id or the found entry as a bonusdid you mean the old
name
maybe? why return id
if it's going to be the same as the passed argument or null (if not found)?dave08
04/07/2021, 9:18 AMarekolek
04/07/2021, 9:20 AMdave08
04/07/2021, 9:22 AMarekolek
04/07/2021, 9:25 AMfun MutableList<Foo>.replace(id: Int, name: String): Foo? {
val index = indexOfFirst { it.id == id }
return if (index > -1) {
set(index, get(index).copy(name = name))
} else {
null
}
}
dave08
04/07/2021, 9:27 AMarekolek
04/07/2021, 9:34 AMfun <T> MutableList<T>.replace(predicate: (T) -> Boolean, transformation: (T) -> T): T? {
val index = indexOfFirst(predicate)
return if (index > -1) {
set(index, transformation(get(index)))
} else {
null
}
}
fun MutableList<Foo>.replace(id: Int, name: String): Foo? {
return replace({ it.id == id }) { it.copy(name = name) }
}
Big Chungus
04/07/2021, 9:37 AMdave08
04/07/2021, 9:38 AMBig Chungus
04/07/2021, 9:41 AMarekolek
04/07/2021, 9:49 AMEven better yet, crossinline lambda args toodoes that change anything in the case above?
Big Chungus
04/07/2021, 9:51 AMBig Chungus
04/07/2021, 9:51 AMarekolek
04/07/2021, 10:52 AMinline
does? bytecode seems to be exactly the same with and without crossinline
ephemient
04/07/2021, 3:56 PMephemient
04/07/2021, 3:59 PMephemient
04/07/2021, 6:11 PMarekolek
04/07/2021, 7:14 PMephemient
04/07/2021, 7:50 PMdave08
04/08/2021, 10:00 AMfun <T> MutableList<T>.modify(predicate: (T) -> Boolean, transformation: T.() -> Unit): T? {
val iterator = listIterator()
while (iterator.hasNext()) {
val value = iterator.next()
if (predicate(value)) return value.also { value.transformation() }
}
return null
}