Kotlin List dropLast()
Syntax & Examples
Syntax of List.dropLast()
The syntax of List.dropLast() extension function is:
fun <T> List<T>.dropLast(n: Int): List<T>
This dropLast() extension function of List returns a list containing all elements except last n elements.
✐ Examples
1 Example
In this example,
- We create a list of integers
list
. - We use the
dropLast
function with the argument2
to drop the last two elements from the list. - The resulting list
result
contains elements1, 2, 3, 4
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 6)
val result = list.dropLast(2)
print(result)
}
Output
[1, 2, 3, 4]
2 Example
In this example,
- We create a list of characters
list
. - We use the
dropLast
function with the argument3
to drop the last three elements from the list. - The resulting list
result
contains elementsa
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "b", "c", "d")
val result = list.dropLast(3)
print(result)
}
Output
[a]
3 Example
In this example,
- We create a list of strings
list
. - We use the
dropLast
function with the argument1
to drop the last element from the list. - The resulting list
result
contains elementsapple, banana, mango
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "mango", "avocado")
val result = list.dropLast(1)
print(result)
}
Output
[apple, banana, mango]
Summary
In this Kotlin tutorial, we learned about dropLast() extension function of List: the syntax and few working examples with output and detailed explanation for each example.