Kotlin List get()
Syntax & Examples
Syntax of List.get()
The syntax of List.get() function is:
abstract operator fun get(index: Int): EThis 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
list1containing the elements'a', 'b', 'c', 'd'. - We retrieve the element at index
2using the Listget()function, which returns the element at the specified index. - The element at index
2inlist1is'c', soelementAtIndex2will be'c'. - Finally, we print the value of
elementAtIndex2to standard output using theprintlnfunction.
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
list1containing the elements10, 20, 30, 40. - We retrieve the element at index
3using the Listget()function, which returns the element at the specified index. - The element at index
3inlist1is40, soelementAtIndex3will be40. - Finally, we print the value of
elementAtIndex3to standard output using theprintlnfunction.
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.