Kotlin List get()
Syntax & Examples


Syntax of List.get()

The syntax of List.get() function is:

abstract operator fun get(index: Int): E

This get() function of List returns the element at the specified index in the list.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the elements 'a', 'b', 'c', 'd'.
  • We retrieve the element at index 2 using the List get() function, which returns the element at the specified index.
  • The element at index 2 in list1 is 'c', so elementAtIndex2 will be 'c'.
  • Finally, we print the value of elementAtIndex2 to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d")
    val elementAtIndex2 = list1.get(2)
    println(elementAtIndex2)
}

Output

c

2 Example

In this example,

  • We create a list named list1 containing the elements 10, 20, 30, 40.
  • We retrieve the element at index 3 using the List get() function, which returns the element at the specified index.
  • The element at index 3 in list1 is 40, so elementAtIndex3 will be 40.
  • Finally, we print the value of elementAtIndex3 to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30, 40)
    val elementAtIndex3 = list1.get(3)
    println(elementAtIndex3)
}

Output

40

Summary

In this Kotlin tutorial, we learned about get() function of List: the syntax and few working examples with output and detailed explanation for each example.