Kotlin provides several functions to retrieve elements from collections efficiently. Three commonly used functions are first, last, and single. These functions offer simple and expressive ways to access specific elements under different conditions.
1. Using first in Kotlin
The first function returns the first element of a collection. If the collection is empty, it throws a NoSuchElementException. You can also specify a condition using a lambda expression to find the first element that matches a given predicate.
Examples:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Get the first element
val firstNum = numbers.first()
println("First number is: $firstNum") // Output: First number is: 1
// Get the first even number
val firstEven = numbers.first { it % 2 == 0 }
println("First even number is: $firstEven") // Output: First even number is: 2
}
2. Using last in Kotlin
The last function works similarly to first, but it returns the last element of a collection. If no element satisfies the given condition or the collection is empty, it throws a NoSuchElementException.
Examples:
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry", "Date")
// Get the last element
val lastFruit = fruits.last()
println("Last fruit is: $lastFruit") // Output: Last fruit is: Date
// Get the last fruit that starts with 'C'
val lastFruitWithC = fruits.last { it.startsWith('C') }
println("Last fruit starting with C is: $lastFruitWithC") // Output: Last fruit starting with C is: Cherry
}
3. Using single in Kotlin
The single function returns the only element that matches a given condition. If there is no element or if more than one element satisfies the condition, it throws an IllegalArgumentException.
Examples:
fun main() {
val numbers = listOf(1, 3, 5, 7)
// Get the single element that is greater than 4 but less than 6
val singleNum = numbers.single { it > 4 && it < 6 }
println("Single number is: $singleNum") // Output: Single number is: 5
// This would throw an exception because more than one element matches the condition
// val invalidSingle = numbers.single { it % 2 != 0 }
}
Conclusion
The functions first, last, and single provide convenient ways to retrieve elements from collections in Kotlin with respect to specified conditions. While using them, it's crucial to handle potential exceptions appropriately to maintain robust code.