How to use the takeLast method of list in Kotlin
Overview
The takeLast method gets the last n elements of the current List as a new List.
Syntax
fun <T> List<T>.takeLast(n: Int): List<T>
Arguments
This method takes a positive integer value as an argument. This denotes the number of elements that should be taken from the end of the List. We will get IllegalArgumentException if the argument is negative.
Return value
This method returns a new List containing the last n elements of the List.
Code
The code below demonstrates the use of the takeLast method in Kotlin:
fun main() {//create another list with elementsval list = listOf(1,2,3,4,5)println("\nlist.takeLast(2) : ${list.takeLast(2)}")println("\nlist.takeLast(3) : ${list.takeLast(3)}")println("\nlist.takeLast(4) : ${list.takeLast(4)}")}
Code explanation
- Line 4: We create a list named
listusing thelistOfmethod. Thelistwill have five elements—1,2,3,4,5.
- Line 5: We use the
takeLastmethod with2as an argument. ThetakeLastmethod returns a newListcontaining the last two elements [4,5] of thelistobject.
- Line 6: We use the
takeLastmethod with3as an argument. ThetakeLastmethod returns a newListcontaining the last three elements [3,4,5] of thelistobject.
- Line 7: We used the
takeLastmethod with4as an argument. ThetakeLastmethod returns a newListcontaining the last four elements [2,3,4,5] of thelistobject.