Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get list managed correctly in Kotlin?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading