Kotlin List.component1() Function
The Kotlin List.component1() function returns the first element in this list.
Syntax of List.component1()
The syntax of List.component1() function is
</>
Copy
list.component1()
Return Value
Kotlin List.component1() function returns first element from the list.
Example 1: Get First Element in List
In this example, we will take a list of elements of string type, and get the first element programmatically using List.component1() function.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
val first = list1.component1()
print("First element is : \"$first\"")
}
Output
First element is : "ab"
Example 2: List.component1() with Empty List
If you call component1() function on an empty list, the function throws java.lang.IndexOutOfBoundsException. Let us check with a Kotlin example program.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
val list1 = listOf<String>()
val first = list1.component1()
print("First element is : \"$first\"")
}
Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Empty list doesn't contain element at index 0.
at kotlin.collections.EmptyList.get(Collections.kt:35)
at kotlin.collections.EmptyList.get(Collections.kt:23)
at HelloWorldKt.main(HelloWorld.kt:3)
Conclusion
In this Kotlin Tutorial, we learned how to get the first element of a list, using Kotlin List.component1() function.