Kotlin List.component1()
The Kotlin List.component1() function returns first element from the list.
Syntax
List.component1()
Example 1
In this example,
- Take a list with one or more elements.
- Call component1() function on the list. The function should return the first element.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c")
val result = list1.component1()
print(result)
}
Output
a
Example 2
In this example,
- Take an empty list, i.e., List with no elements.
- Call component1() function on the list. As there no at least one element in the list, the function should throw java.lang.ArrayIndexOutOfBoundsException.
Program
fun main(args: Array<String>) {
val list1 = listOf<String>()
val result = list1.component1()
print(result)
}
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 KotlinExampleKt.main(KotlinExample.kt:3)