Safe Call Operator (?.) in Kotlin


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