Kotlin String - getOrNull() Function



The Kotlin string getOrNull() function is used to retrieve the character at the specified index but returns null instead of throwing an exception if the index is out of bounds. It eliminates the risk of throwing an 'indexOutOfBoundException'.

Syntax

Following is the syntax of the Kotlin string getOrNull() function −

fun CharSequence.getOrNull(index: Int): Char?

Parameters

This function accepts an index number as a parameter.

Return value

If the given index is valid then return the character. Otherwise, return null.

Example 1: Display char at Index First

Following is the basic example, here how we can use getOrNull() with string in Kotlin −

fun main() {
   val str = "tutorialspoint"
   val char = str.getOrNull(1);
   println("char at index 1: ${char}")
}

Output

Following is the output −

char at index 1: u

Example 2: If Index is Out of Bound

Now, let's look at another example of the getOrNull() function, if the index is out of bound.

fun main() {
   val str = "Aman"
   val char = str.getOrNull(5);
   println("char at index 5: ${char}")
}

Output

If the index is out of bound −

char at index 5: null

Example 3: What if the String is Empty

Here, in this example the getOrNull function returns NULL If the string is empty −

fun main() {
   val str = ""
   val char = str.getOrNull(0);
   println("char at index 0: ${char}")
}

Output

char at index 0: null
kotlin_strings.htm
Advertisements