Kotlin is a modern programming language that runs on the Java Virtual Machine (JVM) having compact syntax. It is used by developers for various applications, spanning from Android app development to backend services.
getOrElse()
methodThe getOrElse()
method handles nullable values and provides ?
modifier.
The syntax for the getOrElse()
method is given below:
fun <T> T?.getOrElse(defaultValue: () -> T): T
<T>
represents the type of the object being operated on.
T?
is the receiver object on which the method is invoked which can be nullable.
defaultValue
is a lambda function that returns the default value to be used if the receiver object is null.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
Let's look at the code below to demonstrate the use of the getOrElse()
method.
Suppose we have a map of students with their names and grades and want to retrieve the (value) grade of some students from the map, providing a default value if the key (name of the student) is not found.
fun main() {val studentGrades = mapOf("Alice" to 95, "Bob" to 88, "Eve" to 72)val studentName = "Charlie"val charlieGrade = studentGrades.getOrElse(studentName) { -1 }println("Grade of $studentName: $charlieGrade")}
Line 1–2: Firstly, we create a map that associates student names with their respective grades.
Line 4: Next, we specify the student name for which we want to retrieve the grade.
Line 5: Here, we use the getOrElse()
method on the value associated with the studentName
key in the studentGrades
map.
Line 7: Finally, we print the student's name and their grade (or default grade) on the console.
Upon execution, the code provides a fallback mechanism since there is no student named “Charlie” in the studentGrades
map and this method will execute the lambda function and provide the default grade of -1.
The output looks something like this:
Grade of Charlie: -1
Therefore, Kotlin's getOrElse()
function is an essential tool that simplifies null handling and offers a powerful framework for dealing with nullable objects. It is typically used for its concise syntax, null safety benefits, and flexibility to provide fallback values which makes it a reliable option for guaranteeing code stability for developers.
Free Resources