Vishal Rao
11/26/2022, 9:23 AMlist[2:5] = mlist
This python code assigns mlist into list at indices 2 to 5. I am not able to do the same in kotlin using inbuilt methods. Can anyone help me.Sam
11/26/2022, 9:37 AMlist.subList(2, 5).let {
it.clear()
it.addAll(mList)
}
Sam
11/26/2022, 9:43 AMval newList = list.take(2) + mList + list.drop(5)
ephemient
11/26/2022, 3:00 PMval newList = buildList {
addAll(list.subList(0, 2))
addAll(mList)
addAll(list.subList(5, list.size))
}
with a small list it doesn't matter, but if you're splicing many parts together, this is better than repeated List::plus
. also, depending on your problem, perhaps a different data structure would work betterRuckus
11/26/2022, 4:08 PMoperator fun <T> MutableList<T>.set(
slice: IntRange,
values: List<T>,
) {
val sub = subList(
slice.start,
slice.endInclusive,
}
sub.clear()
sub.addAll(values)
}
// Use
list[2..5] = mList
Sam
11/26/2022, 4:15 PM2..5
could be misleading, as it implies a closed range, whereas subList
doesn't include the upper bound.Sam
11/26/2022, 4:17 PMval sub = subList(slice.start, slice.endExclusive)
and then use list[2..<5] = mList
Ruckus
11/26/2022, 4:19 PMlist[2, 5] = mList
Vishal Rao
11/26/2022, 6:29 PM