Kotlin String - get() Function



The Kotlin string get() function is used to retrieve the character of the string at the specified index.

Since strings are zero-based indexes, the valid range for get() is from 0 to string.length - 1. If the specified index is out of this range, this function throws an IndexOutOfBoundsException.

Syntax

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

fun get(index: Int): Char

Parameters

This function accepts a single parameter, the index value represents the character you want to return.

Return value

This function returns the character.

Example 1: Get the Element at Index 7

Following is the basic example, here how we can use get() with a string in kotlin −

fun main(){
   val text = "Hello, tutorialspoint"
   val charAtIndex = text.get(7)
   println("Character at index 7: $charAtIndex")
}

Output

text.get(7) retrieves the character at index 7 −

Character at index 7: t

Example 2: If the Index is Out of Bound

Now, let's see another example. If the index out of bounds, then get() function throw the following exception −

fun main(){
   val text = "Hello World!"
   val charAtIndex = text.get(12)
   println("Character at index 10: $charAtIndex")
}

Output

Following is the Output −

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12

Example 3: Handle Exception by using Try-Catch

In this example, we handle the IndexOutOfBoundsException when accessing a character at a specific index, we can use a try-catch block in Kotlin −

fun main() {
   val text = "Hello World!"
   try {
      val charAtIndex = text.get(12)
      println("Character at index 12: $charAtIndex")
   } catch (e: IndexOutOfBoundsException) {
      println("Exception caught: ${e.message}")
   }
}

Output

Since the text string has a length of 12, the valid index range is 0-11. Attempting to access index 12 triggers an IndexOutOfBoundsException, which is then caught and handled by the catch block.

Exception caught: String index out of range: 12
kotlin_strings.htm
Advertisements