Kotlin List getOrNull()
Syntax & Examples
Syntax of List.getOrNull()
The syntax of List.getOrNull() extension function is:
fun <T> List<T>.getOrNull(index: Int): T?This getOrNull() 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 of integers named
list1. - We use the
getOrNull()function with index 2 onlist1to retrieve the element at index 2 or null if the index is out of bounds. - The result, which is an integer or null, is stored in
element. - Finally, we print the value of
elementto standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val element = list1.getOrNull(2)
println(element)
}Output
3
2 Example
In this example,
- We create a list of characters named
list2. - We use the
getOrNull()function with index 5 onlist2to retrieve the element at index 5 or null if the index is out of bounds. - The result, which is a character or null, is stored in
element. - Finally, we print the value of
elementto standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c')
val element = list2.getOrNull(5)
println(element)
}Output
null
3 Example
In this example,
- We create a list of strings named
list3. - We use the
getOrNull()function with index 1 onlist3to retrieve the element at index 1 or null if the index is out of bounds. - The result, which is a string or null, is stored in
element. - Finally, we print the value of
elementto standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry")
val element = list3.getOrNull(1)
println(element)
}Output
banana
Summary
In this Kotlin tutorial, we learned about getOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.