The takeLast
method gets the last n
elements of the current List
as a new List
.
fun <T> List<T>.takeLast(n: Int): List<T>
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.
This method returns a new List
containing the last n
elements of the List
.
The code below demonstrates the use of the takeLast
method in Kotlin:
fun main() { //create another list with elements val 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)}") }
list
using the listOf
method. The list
will have five elements— 1,2,3,4,5
.takeLast
method with 2
as an argument. The takeLast
method returns a new List
containing the last two elements [4,5] of the list
object.takeLast
method with 3
as an argument. The takeLast
method returns a new List
containing the last three elements [3,4,5] of the list
object.takeLast
method with 4
as an argument. The takeLast
method returns a new List
containing the last four elements [2,3,4,5] of the list
object.RELATED TAGS
CONTRIBUTOR
View all Courses