Google News
logo
Kotlin - Interview Questions
What is the difference between safe calls(?.) and null check(!!)?
In Kotlin, safe calls (`?.`) and null checks (`!!`) are two different approaches to handle null values and avoid NullPointerExceptions. Here's the difference between them:

1. Safe Calls (`?.`) :
   * Safe calls allow you to safely access properties or call methods on a nullable object.
   * If the object is not null, the property or method is accessed normally.
   * If the object is null, the expression is short-circuited, and the result of the entire expression is null.
   * Safe calls ensure that the code does not throw a NullPointerException.
   Example:
     val length: Int? = text?.length​

2. Null Checks (`!!`) :
   * Null checks assert that an expression is not null.
   * If the expression is not null, it is accessed or used as usual.
   * If the expression is null, a NullPointerException is thrown immediately.
   * Null checks are explicit assertions that you are guaranteeing that the expression is not null.
   Example:
     val length: Int = text!!.length​
Here are some important points to consider when using these operators :

* Safe calls (`?.`) provide a safer approach to accessing properties and methods on nullable objects. They allow you to handle null values gracefully and avoid NullPointerExceptions by returning null instead.

* Null checks (`!!`) are more risky because they explicitly assert that an expression is not null. If the expression is actually null, a NullPointerException will be thrown, potentially causing a program crash.

* Safe calls (`?.`) are typically used when you expect the possibility of a null value and want to handle it gracefully by providing an alternative behavior or a default value.

* Null checks (`!!`) are used when you are certain that an object reference is not null and want to enforce it, bypassing the nullability checks of the compiler. They should be used with caution and only when you are confident that the expression cannot be null.

It's generally recommended to use safe calls (`?.`) and handle null values gracefully by providing appropriate fallback or alternative behaviors. Null checks (`!!`) should be used sparingly and only when you have explicit knowledge that an expression cannot be null.
Advertisement