- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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