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 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)}")
}

Code explanation

  • Line 4: We create a list named list using the listOf method. The list will have five elements— 1,2,3,4,5.
  • Line 5: We use the 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.
  • Line 6: We use the 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.
  • Line 7: We used the 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.

Free Resources