This article explores different ways to determine if an index exists in an array in Kotlin.

Whenever we try to access an array with a negative index or index more than or equal to the array’s length, the java.lang.ArrayIndexOutOfBoundsException is thrown. For instance,

Download Code

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6
    at MainKt.main(Main.kt:5)
    at MainKt.main(Main.kt)

 
We can avoid getting an index out of bounds exception by explicitly checking if the array index is within the bounds of the array before accessing it.

1. Using In operator

The idiomatic way to check if an index exists in an array is using the in operator, which provides concise and readable syntax.

Download Code

Output:

Index 7 out of bounds for length 6

 
The above code can be further shortened using .indices, which returns the range of valid indices for the array.

Download Code

Output:

Index 7 out of bounds for length 6

 
Note that in operator is equivalent to calling the contains() function. The expression x in y is translated to y.contains(x).

Download Code

Output:

Index 7 out of bounds for length 6

2. Using && operator

The array index is valid if it is non-negative and less than the array’s length. We can easily determine if an index is valid using a conditional expression, as follows:

Download Code

Output:

Index 7 out of bounds for length 6

3. Using getOrNull() function

The getOrNull() function returns an element at the given index, or null if the index is out of bounds of the array. It can be used as follows to determine if an index is valid or not.

Download Code

Output:

Index 7 out of bounds for length 6

 
Additionally, the value at the given index can be determined using the let function:

Download Code

Output:

The value present at the index 4 is 9

4. Using try-catch block

Finally, we can just try accessing the array using the indexing operator within a try-catch block. It throws IndexOutOfBoundsException if the index is out of bounds. It can be used as follows:

Download Code

Output:

Index 7 out of bounds for length 6

That’s all about determining if an index exists in an array in Kotlin.