Kotlin List elementAt()
Syntax & Examples
Syntax of List.elementAt()
The syntax of List.elementAt() extension function is:
fun <T> List<T>.elementAt(index: Int): T
This elementAt() extension function of List returns an element at the given index or throws an IndexOutOfBoundsException if the index is out of bounds of this list.
✐ Examples
1 Example
In this example,
- We create a list of integers
list
. - We use the
elementAt
function to get the element at index 2, which is3
. - We print the retrieved element
3
to the standard output usingprintln
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val element = list.elementAt(2)
println(element)
}
Output
3
2 Example
In this example,
- We create a list of characters
list
. - We use the
elementAt
function to get the element at index 1, which isb
. - We print the retrieved element
b
to the standard output usingprintln
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "b", "c")
val element = list.elementAt(1)
println(element)
}
Output
b
3 Example
In this example,
- We create a list of strings
list
. - We use the
elementAt
function to get the element at index 0, which isapple
. - We print the retrieved element
apple
to the standard output usingprintln
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "mango")
val element = list.elementAt(0)
println(element)
}
Output
apple
Summary
In this Kotlin tutorial, we learned about elementAt() extension function of List: the syntax and few working examples with output and detailed explanation for each example.