Kotlin List elementAtOrNull()
Syntax & Examples
Syntax of List.elementAtOrNull()
The syntax of List.elementAtOrNull() extension function is:
fun <T> List<T>.elementAtOrNull(index: Int): T?
This elementAtOrNull() extension function of List returns an element at the given index or null if the index is out of bounds of this list.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the integers10, 20, 30
. - Then we use the
elementAtOrNull
function onlist1
to access the element at index1
. - Since index
1
exists inlist1
, the element at that index, which is20
, is returned. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30);
val result = list1.elementAtOrNull(1)
print(result);
}
Output
20
2 Example
In this example,
- We create a list named
list2
containing the characters'a', 'b', 'c'
. - Then we use the
elementAtOrNull
function onlist2
to access the element at index5
. - Since index
5
is out of bounds forlist2
, the function returnsnull
. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c');
val result = list2.elementAtOrNull(5)
print(result);
}
Output
null
3 Example
In this example,
- We create a list named
list3
containing the strings"apple", "banana", "cherry"
. - Then we use the
elementAtOrNull
function onlist3
to access the element at index10
. - Since index
10
is out of bounds forlist3
, the function returnsnull
. - Finally, we print the value of
result
to standard output using the print statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry");
val result = list3.elementAtOrNull(10)
print(result);
}
Output
null
Summary
In this Kotlin tutorial, we learned about elementAtOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.