Null Safety
Kotlin's defining feature: String can never hold null, only String? can — and ?. and ?: let you work with a nullable value safely instead of crashing.
Nullable types
This is Kotlin's headline feature. A regular type like String can never hold null — the compiler simply won't let you assign it. To allow null, you write String?, explicitly marking the type as nullable:
fun main() {
var name: String = "Priya"
// name = null // would not compile: Null can not be a value of a non-null type String
var nickname: String? = "P"
nickname = null // fine — the type says this is allowed
println(nickname)
}
null
The type system tracks this distinction everywhere. Because name: String can never be null, calling name.length is always safe and needs no null check — an entire category of Java's NullPointerException simply becomes impossible to compile.
The safe call operator ?.
For a nullable type, calling a method directly (nickname.length) won't compile — the compiler forces you to handle the null case. The safe call operator ?. returns null automatically instead of crashing if the value is null:
fun main() {
val nickname: String? = null
val length = nickname?.length
println(length)
}
null
The Elvis operator ?: for a fallback
Chain ?: after a safe call to supply a default value when the result would otherwise be null:
fun main() {
val nickname: String? = null
val length = nickname?.length ?: 0
println("Length: $length")
}
Length: 0
Read a ?: b as "a, or b if a is null" — it's the closest thing Kotlin has to a null-coalescing operator, and it's everywhere in idiomatic Kotlin code.