Safe call operator in Kotlin with example

Published by admin on

Safe call operator in Kotlin :

Safe call operator is denoted by ? in Kotlin. This operator is mainly used to remove null pointer exception or NPE in Kotlin.
In this tutorial, we will learn how to use safe call operator in Kotlin with different use cases.

A simple example :

Let’s try safe call operator with a simple example :

fun main(args: Array) {
   var userInput: String?

   userInput = null

   println(userInput?.length)

}

In this example, the value of userInput is null. But if we try to get the length on this null variable, it will not throw an exception. Instead, it will print ‘null’ as output.
kotlin safe call operator

Chain safe calls :

Safe call operator can be used in chain calls. For example :

student?.className?.totalCount

In this example, we are getting the total count of a specific class for a specific student.
If any of the property is null, this chain expression will return null.

student?.className?.totalCount = getStudentName()

In the above example, we have placed the safe call to the left side of the assignment operator. In this case, if any one member of the safe call chain is null on the left side, the expression on the right side will not be evaluated.

Using safe call with let :

We can use let with safe call operator to check if any value is null or not. e.g. :

fun main(args: Array) {
   var userInput: String?

   userInput = null

   userInput?.let{
       println("$userInput is not null")
   }
}

kotlin safe call operator

In this program, we are checking the value of userInput if it is not-null or null before doing any operation inside the curly braces.

Conclusion :

We hope that you have found this article valuable. If you are familiar to swift, you will find it much more similar to the optional operations. Don’t hesitate to drop one comment below if you have any queries.

You might also like :

Categories: kotlin

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *