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