I have a list of items like
val myList = listOf(1, 2, 3, 4, 5, 6, 7, 8)
and need to take first three elements, whcih I do like this:
myList.take(3).forEach { }
and wnat to get the rest of elements by doing something like this:
myList.restElements.forEach { }
where the extension/function restElements
lists all elements 4
, 5
, 6
, 7
, 8
by jumping over the first three ones.
Is there any short feature in Kotlin for that? Thanks.
1
If you prefer to use an extension function restElements, you can define it like this:
fun <T> List<T>.restElements(n: Int): List<T> = this.drop(n)
fun main() {
val myList = listOf(1, 2, 3, 4, 5, 6, 7, 8)
// Take the first 3 elements
myList.take(3).forEach {
println("First 3 elements: $it")
}
// Use the extension function to get the rest of the elements
myList.restElements(3).forEach {
println("Rest of the elements: $it")
}
}
By using the restElements extension function, you can easily get the remaining elements after skipping the first N elements, making your code more readable and expressive.
1