Null safety and the safe-call operator
Kotlin distinguishes a value that must exist (String) from one that may be absent (String?). This moves many failures from runtime into compiler feedback.
val nickname: String? = null
val length: Int? = nickname?.length
When nickname is null, nickname?.length returns null. It does not return zero. An empty string exists and therefore has length zero; absence and emptiness are different states.
null; empty nickname → 0; Rakesh → 6. The Elvis operator converts only the missing result to the chosen default.What is !!?
!! is the not-null assertion operator. It tells Kotlin to treat a nullable value as non-null. If the value is actually null, the expression throws NullPointerException.
!! does not validate a value. It disables the compiler’s nullable-type protection at that location.
Android scenario
An Android navigation value can be missing, empty, or contain real text:
null: the value was not supplied."": the value was supplied but is empty."Rakesh": the value contains usable text.
If you immediately replace null with "", you lose the difference between “missing” and “empty.” That can produce incorrect analytics, validation, or repository calls. Choose a default only when both states truly mean the same thing in your feature.
The safe-call operator ?. accesses the next value only when the receiver is non-null. If nickname is null, nickname?.length returns null and its type is Int?; it does not return zero.
Interview check
What happens when nickname is null?
The result is null, and the inferred type is Int?. The safe call conditionally accesses length and propagates absence.