Safe Call Operator (?.) in Kotlin
On this page (6sections)
Definition
- This operator helps in writing a program without NPEs (Null Pointer Exceptions) and is represented by (?.)
- This operator eliminates exception and returns the response as null when a null value is used for any operation.
Syntax
//When the nullable_value is null, the block inside the let will not be executed.
var result = nullable_value?.let{
//Block of code
}
For example,
//While doing operations or iterating with a collection which may have null values, this operator can be used to eliminate Null Pointer Exception.
var result = value_in_collection?.let{
//"it" is a variable generated by Kotlin and it holds the particular non-null value of the collection.
println(it)
}
Safe Call Operator Example Program in Kotlin
//Safe Call Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
//List containing null values
val namesList = listOf("Sheela", null, "Leela")
println("List containing null values is : $namesList")
//Iterating the list
println("\nIterating the non-null values in list")
for (value in namesList) {
//Safe Call Operator allows only the non-null values inside the let block
value?.let {
//Printing the non-null value
println(it)
}
}
}
Sample Output
List containing null values is : [Sheela, null, Leela]
Iterating the non-null values in list
Sheela
Leela
How It Works
This Kotlin program demonstrates Safe Call Operator (?.). It first prepares the data it needs, then walks through the data with a loop to compute the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Iterate over the data using a loop to apply the logic.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Safe Call Operator (?.) in Kotlin?
This operator helps in writing a program without NPEs (Null Pointer Exceptions) and is represented by (?.)
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Safe Call Operator (?.)?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.