Skip to content

Instantly share code, notes, and snippets.

@crowjdh
Created May 3, 2016 15:18
Show Gist options
  • Save crowjdh/92446422aab1b01709665c9afab0afa4 to your computer and use it in GitHub Desktop.
Save crowjdh/92446422aab1b01709665c9afab0afa4 to your computer and use it in GitHub Desktop.
Remove items with range from MutableList in Kotlin
inline fun <reified T> MutableList<T>.removeRange(range: IntRange) {
val fromIndex = range.start
val toIndex = range.last
if (fromIndex == toIndex) {
return
}
if (fromIndex >= size) {
throw IndexOutOfBoundsException("fromIndex $fromIndex >= size $size")
}
if (toIndex > size) {
throw IndexOutOfBoundsException("toIndex $toIndex > size $size")
}
if (fromIndex > toIndex) {
throw IndexOutOfBoundsException("fromIndex $fromIndex > toIndex $toIndex")
}
val filtered = filterIndexed { i, t -> i < fromIndex || i > toIndex }
clear()
addAll(filtered)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment