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 is 3.
  • We print the retrieved element 3 to the standard output using println.

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 is b.
  • We print the retrieved element b to the standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)
    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 is apple.
  • We print the retrieved element apple to the standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;)
    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.