Kotlin Array drop()
In Kotlin, the drop()
function is used to exclude the first N elements of the original array. It returns a list with the specified number of elements dropped from the beginning of the original array.
This function is useful when you need to skip a certain number of elements at the beginning of an array.
In this tutorial, we’ll explore the syntax of the Array drop()
function and provide examples of its usage in Kotlin.
Syntax
The syntax of the Array drop()
function is as follows:
fun <T> Array<out T>.drop(n: Int): List<T>
where
Parameter | Description |
---|---|
n | An integer value. |
The drop()
function takes an integer n
as an argument, indicating the number of elements to drop from the beginning of the array. It returns a new list containing the remaining elements.
Examples
1. Using drop() to Skip the First 3 Numbers
In this example, we’ll use drop()
to exclude the first 3 numbers from the original array of integers numbersArray
.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
// Using drop() to skip the first 3 numbers
val result = numbersArray.drop(3)
// Printing the original array and the result
println("Given Array: \n${numbersArray.joinToString(", ")}\n")
println("Result (After Dropping First 3 Numbers): \n${result.joinToString(", ")}")
}
Output
Given Array:
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Result (After Dropping First 3 Numbers):
40, 50, 60, 70, 80, 90, 100
2. Using drop() to Skip Elements in a String Array
In this example, we’ll use drop()
to skip a specified number of elements from the beginning of a String array.
Kotlin Program
fun main() {
val fruitsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
// Using drop() to skip the first 2 fruits
val result = fruitsArray.drop(2)
// Printing the original array and the result
println("Fruits: \n${fruitsArray.joinToString(", ")}\n")
println("Result (After Dropping First 2 Fruits): \n${result.joinToString(", ")}")
}
Output
Fruits:
apple, banana, orange, grape, kiwi
Result (After Dropping First 2 Fruits):
orange, grape, kiwi
3. Using drop() with a Larger Number
In this example, we’ll use drop()
with a larger number to skip more elements than the array contains, resulting in an empty list.
Kotlin Program
fun main() {
val fruitsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
// Using drop() with a larger number to skip more elements than the array contains
val result = fruitsArray.drop(10)
// Printing the original array and the result
println("Fruits: \n${fruitsArray.joinToString(", ")}\n")
println("Result (After Dropping 10 Elements): \n${result.joinToString(", ")}")
}
Output
Fruits:
apple, banana, orange, grape, kiwi
Result (After Dropping 10 Elements):
Summary
In this tutorial, we’ve covered the drop()
function in Kotlin arrays, its syntax, and how to use it to exclude a specified number of elements from the beginning of given array.