Kotlin List.first()
The Kotlin List.first() function is used to get the first element of this List.
Syntax
The syntax of List.first() function is
</>
Copy
fun <T> List<T>.first(): T
Examples
In the following example, we take a list of strings, and get the first element using List.first() function.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
var list = listOf("apple", "banana", "cherry", "avocado")
var result = list.first()
println(result)
}
Output
apple
In the following example, we take a list of numbers, and get the first element using List.first() function.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
var list = listOf(2, 4, 6, 8)
var result = list.first()
println("First Element : " + result)
}
Output
First Element : 2
If the array is empty, then List.first() returns NoSuchElementException.
In the following example, we take an empty list of integers, and try to get the first element using List.first() function.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
var list = listOf<Int>()
var result = list.first()
println("First Element : " + result)
}
Output
Exception in thread "main" java.util.NoSuchElementException: List is empty.
at kotlin.collections.CollectionsKt___CollectionsKt.first(_Collections.kt:212)
at MainKt.main(Main.kt:3)
Conclusion
In this Kotlin Tutorial, we learned how to get the first element of this List, using Kotlin List.first() function.
