Kotlin List drop()
Syntax & Examples
Syntax of List.drop()
The syntax of List.drop() extension function is:
fun <T> Iterable<T>.drop(n: Int): List<T>This drop() extension function of List returns a list containing all elements except first n elements.
✐ Examples
1 Example
In this example,
- We create a list of integers
list. - We use the
dropfunction with the argument2to drop the first two elements from the list. - The resulting list
resultcontains elements3, 4, 5, 6. - 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.drop(2)
print(result)
}Output
[3, 4, 5, 6]
2 Example
In this example,
- We create a list of characters
list. - We use the
dropfunction with the argument3to drop the first three elements from the list. - The resulting list
resultcontains elementsd. - 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.drop(3)
print(result)
}Output
[d]
3 Example
In this example,
- We create a list of strings
list. - We use the
dropfunction with the argument1to drop the first element from the list. - The resulting list
resultcontains elementsbanana, mango, avocado. - 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.drop(1)
print(result)
}Output
[banana, mango, avocado]
Summary
In this Kotlin tutorial, we learned about drop() extension function of List: the syntax and few working examples with output and detailed explanation for each example.