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 Listget()
function, which returns the element at the specified index. - The element at index
2
inlist1
is'c'
, soelementAtIndex2
will be'c'
. - Finally, we print the value of
elementAtIndex2
to standard output using theprintln
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 elements10, 20, 30, 40
. - We retrieve the element at index
3
using the Listget()
function, which returns the element at the specified index. - The element at index
3
inlist1
is40
, soelementAtIndex3
will be40
. - Finally, we print the value of
elementAtIndex3
to standard output using theprintln
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.