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
dropLastfunction with the argument2to drop the last two elements from the list. - The resulting list
resultcontains elements1, 2, 3, 4. - Finally, we print the
resultlist 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
dropLastfunction with the argument3to drop the last three elements from the list. - The resulting list
resultcontains elementsa. - Finally, we print the
resultlist 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
dropLastfunction with the argument1to drop the last element from the list. - The resulting list
resultcontains elementsapple, banana, mango. - Finally, we print the
resultlist 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.