Updated July 6, 2023
Introduction to Kotlin Optional
Kotlin optional is used to gracefully handle our program’s empty or null values. This type is used at the time of performing API calls which were used to return null values. The Java optional type introduces the new class, allowing our variables to return empty values. The most common pitfall in many programming languages is that accessing members of null reference results in the exception of a null reference. We are using null instead of Java. We are using an optional keyword to tackle this situation. It is very important and useful.
Overview of Kotlin Optional
The possible cause of kotlin NPE is that it is an explicit call for throwing the null pointer exception. In kotlin, the type system distinguishes between references that hold null values. Kotlin will natively support the nullable types when making optional types and all the APIs it will provide. Kotlin supports the nullable types, making nullable types optional and providing all API. In kotlin, an optional type will compare and translate into the nullable types kotlin; in kotlin, we use nullable types.
Types of Kotlin Optional
Below are the optional types available in kotlin as follows. It contains optional and nullable properties.
1. Optional Properties and Nullable Types
Using optional as field types and nullable types, the function of return types is considered valid and idiomatic in kotlin. Instead of using optional types in kotlin, we will declare the null property of the field as below. In the example below, we declared the interface name as a student and provided the two values with the interface.
Code:
interface student {
val stud_name: String
val stud_no: Int?
}
Output:
2. Safe Call Operator
In the below example, stud_name and stud_age are optional; we are forced to use a flatmap method when retrieving the student’s age. In kotlin, we use a safe-call operator to access nullable type properties. The below example shows the safe call operator as follows.
Code:
interface school {
val stud: student
}
val stud_name: stud_name? = getNextstudIfPresent ()
val stud_age: Int? = stud_name?.stud?.age
Output:
3. Let Function
In kotlin, we use the let function to invoke the external function within safe class operators. The below example shows the let function in kotlin as follows.
Code:
val student: student? = stud_name?.stud_age?.let {
Service.getStudenName(it)
}
Output:
4. Elvis Operator
At the time of chain, map calls are returning age, which is non-empty; otherwise, it will provide the fallback value as zero. The below example shows Elvis operator in kotlin as follows.
Code:
val isOfLegalAge: Boolean = school?.student?.age ?: 0 > 10
Output:
5. Assertion Operator and Take If Function
In kotlin, we use an assertion operator instead of the optional get function, which was used in Java. Also, we are using the take-if function in kotlin instead of the optional filter method in Java. The below example shows an assertion operator and takes the if function in kotlin.
Code:
val stud: student? = school?.stud?.takeIf { it.age ?: 0 < 10}
val isOfLegalAge: Boolean = school?.student?.age!! > 10
Output:
Kotlin Optional Alternative
When migrating the projects from Java to kotlin, we need to check the optional object we have used in our project.
Given below are the alternative we are using in kotlin:
1. In the kotlin equivalent of assigning the empty value, we must assign the null value as follows.
Java Code:
Optional<String> stud = Optional.empty ();
Output:
Kotlin Code:
val stud: String? = null
Output:
2. In Java, the of method creates the optional if the value is present. In kotlin, we are throwing the exception by using the throw method.
Java Code:
Optional<String> stud1 = Optional.of ("ABC");
Optional<String> stud2 = Optional.of (null);
Output:
Kotlin Code:
val stud1: String? = "ABC"
val stud2: String? = null
?: throw NullPointerException ()
Output:
3. The of nullable method works the same as of method instead of throwing the exception of the null pointer. The null value will produce the empty.
Java Code:
Optional<String> stud1 = Optional.ofNullable ("ABC");
Optional<String> stud2 = Optional.ofNullable (null);
Kotlin Code:
val stud1: String? = "ABC"
val stud2: String? = null
Output:
4. Is the present method used to present value testing from kotlin as easily as compared to the null value as follows.
Java Code:
if (stud.isPresent ()) {
System.out.println("stud is present");
}
Output:
Code:
if (present != null) {
println("stud is present")
}
Output:
5. The nullable types in kotlin are not wrapped into the other class. There is an equivalent to the get method.
Java Code:
String stud1 = stud1.get ();
String stud2 = stud2.get ();
Output:
Kotlin Code:
val stud1 = stud1
val stud2 = stud2 ?: throw NoSuchElementException ()
Output:
In the above example, we can see that we are using null types instead of optional in kotlin, while in Java, we are using optional.
Kotlin Optional Data Class Filed
In kotlin, the data class represents the object of the data container. By default, it will expose the primary constructor, which requires all the following fields.
Code:
class student(
val studname: String,
val surname: String,
val studage: Number
)
Output:
By default, in the data class, all fields are mandatory in the primary constructor. In the below example, we are writing a new class as follows.
Code:
class student1 (
val studname? = null,
val surname? = null,
val studage? = null
)
Output:
To eliminate the null ability in this step, we are setting up the default value of the primary constructor.
Code:
class student2 (
val studname: String = "",
val surname: String = "",
val studage: Number = Int.MIN_VALUE
)
Output:
Instead of default values, we are creating the secondary constructor with the following default values.
Code:
class student3 (
val studname: String
) {
constructor() : this("", "ABC", Int.MIN_VALUE)
}
Output:
Conclusion
In kotlin, the type system distinguishes between references that hold null values. Kotlin will natively support the nullable types. This type is used at the time of performing API calls which were used to return null values.
Recommended Articles
We hope that this EDUCBA information on “Kotlin Optional” was beneficial to you. You can view EDUCBA’s recommended articles for more information.