Kotlin List.dropLast() – Examples

Kotlin List.dropLast()

The Kotlin List.dropLast() function returns a list containing all elements except last n elements.

Syntax

List.dropLast(n)

Example 1

In this example,

  1. Take a list of elements: list1.
  2. Take a value for n, say 2.
  3. Call dropLast() function on the list and pass n as argument to it. The return value should be a list, without the last n (=2) elements of list1.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e")
    val n = 2
    val result = list1.dropLast(n)
    print(result)
}

Output

[a, b, c]

Example 2

In this example,

  1. Take a list of elements: list1.
  2. Take a value for n, such that n is greater than the length of list1.
  3. Call dropLast() function on the list and pass n as argument to it. As n is greater than list1.size, the retuned list should be an empty list.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e")
    val n = 20
    val result = list1.dropLast(n)
    print(result)
}

Output

[]