Kotlin Array - dropLast() Function



The Kotlin array dropLast() function is used to retrieve the list contains the all elements except the last n element from an array. Where, n is the number that must be passed to the dropLast function in order to remove the element from last to n. Following is the exceptions of this function −

  • IllegalArgumentException: This exception is thrown if n is negative.

Syntax

Following is the syntax of Kotlin array dropLast() function −

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

Parameters

This function accepts a parameter (n), which represents the number of elements from the ending of the array that need to be dropped.

Return value

This function returns a list containing all the array elements left after being dropped.

Example 1

Following is the basic example to demonstrate the use of dropLast() function −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val after_dropLast = number.dropLast(4)
   println("list after dropLastped: $after_dropLast")
}

Output

On execution of the above code we get the following result −

list after dropLastped: [1, 2, 3, 4]

Example 2

Now, let's see another example. We create an array that stores string. We then use the dropLast() function to drop last 2 elements −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val after_dropLast = strings.dropLast(2)
   println("list after dropLastped: $after_dropLast")
}

Output

After execution of the above code we get the following output −

list after dropLastped: [hii, Hello]

Example 3

The example below creates an array of 26 characters. We then use dropLast() to drop last 10 element −

fun main(args: Array<String>) {
   // Create an array of characters from 'a' to 'z'
   val alphabet: Array<Char> = ('a'..'z').toList().toTypedArray()
   
   // Drop the last 10 elements from the array
   val after_Drop = alphabet.dropLast(10)
   
   println("List after dropLastping the first 10 elements: $after_Drop")
}

Output

The above code produce following output −

List after dropLastping the first 10 elements: [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]
kotlin_arrays.htm
Advertisements