getOrNull

fun <T> Array<out T>.getOrNull(index: Int): T?(source)

Returns an element at the given index or null if the index is out of bounds of this array.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val list = listOf(1, 2, 3)
println(list.getOrNull(0)) // 1
println(list.getOrNull(2)) // 3
println(list.getOrNull(3)) // null

val emptyList = emptyList<Int>()
println(emptyList.getOrNull(0)) // null 
   //sampleEnd
}

fun <T> List<T>.getOrNull(index: Int): T?(source)

Returns an element at the given index or null if the index is out of bounds of this list.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val list = listOf(1, 2, 3)
println(list.getOrNull(0)) // 1
println(list.getOrNull(2)) // 3
println(list.getOrNull(3)) // null

val emptyList = emptyList<Int>()
println(emptyList.getOrNull(0)) // null 
   //sampleEnd
}

Returns an element at the given index or null if the index is out of bounds of this array.

Since Kotlin

1.3

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val list = listOf(1, 2, 3)
println(list.getOrNull(0)) // 1
println(list.getOrNull(2)) // 3
println(list.getOrNull(3)) // null

val emptyList = emptyList<Int>()
println(emptyList.getOrNull(0)) // null 
   //sampleEnd
}