Kotlin List.dropLast() Function

The Kotlin List.dropLast() function is used to delete last n elements from this List. n is passed as argument to dropLast() method. dropLast() method does not modify the original list, but creates a new list and returns it.

Syntax of List.dropLast()

The syntax of List.dropLast() function is

</>
Copy
fun <T> List<T>.dropLast(n: Int): List<T>

Returns

List.

Examples

In this example, we take a list with five elements. We drop the last two elements using dropLast() function.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf(2, 4, 6, 8, 10)
    var result = list.dropLast(2)
    println(result)
}

Output

[2, 4, 6]

If the n passed as argument to dropLast() is greater than the length of list, then dropLast() returns an empty list.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf(2, 4, 6, 8, 10)
    var result = list.dropLast(7)
    println(result)
}

Output

[]

Conclusion

In this Kotlin Tutorial, we learned how to drop last n elements of given list, using Kotlin List.dropLast() function.