Kotlin List.component3()
The Kotlin List.component3() function returns third element from the list.
Syntax
List.component3()
Example 1
In this example,
- Take a list with three or more elements.
- Call component3() function on the list. The function should return the third element.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d")
val result = list1.component3()
print(result)
}
Output
c
Example 2
In this example,
- Take a list with less than three elements.
- Call component3() function on the list. As there no at least three elements in the list, the function should throw java.lang.ArrayIndexOutOfBoundsException.
Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b")
val result = list1.component3()
print(result)
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4350)
at KotlinExampleKt.main(KotlinExample.kt:3)