`list[2:5] = mlist` This python code assigns mlist...
# getting-started
v
list[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.
s
I can't think of one call that will do the whole thing, but you could use two sublist operations, like this:
Copy code
list.subList(2, 5).let {
    it.clear()
    it.addAll(mList)
}
And since we're in Kotlin and we love immutability, here's a more idiomatic version, which returns a new list rather than mutating the existing one:
Copy code
val newList = list.take(2) + mList + list.drop(5)
K 2
e
this has fewer intermediates copies:
Copy code
val 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 better
👍 1
r
You can define an extension
Copy code
operator 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
👌 4
1
s
That's clever! And actually feels pretty clean to me. However using
2..5
could be misleading, as it implies a closed range, whereas
subList
doesn't include the upper bound.
To match the OP, I'd change the implementation to
val sub = subList(slice.start, slice.endExclusive)
and then use
list[2..<5] = mList
r
Agreed, I was just trying to match the syntax as close as possible. I would personally probably just use two args
list[2, 5] = mList
v
Thanks guys, lot's of insight