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