NullPointerException (NPE) is one of the most common crashes in Java apps. Kotlin was designed to prevent it: the compiler knows which variables can be null, and it won’t let you use them unsafely.
Page Contents
Nullable and non-nullable types
By default, a Kotlin variable can’t hold null. Add ? to the type to allow it:
var name: String = "Asha" name = null // ❌ doesn't compile var nickname: String? = "Ash" nickname = null // ✅ String? allows null
Because nickname might be null, Kotlin won’t let you call nickname.length directly. You have to handle the null case first, using one of the tools below.
Safe call: ?.
?. calls the function only if the value isn’t null. Otherwise, the whole expression is null:
fun main() {
val city: String? = "Pune"
val country: String? = null
println(city?.length)
println(country?.length)
println(country?.uppercase()?.reversed()) // chains stop at the first null
}Output:
4 null null
Elvis operator: ?:
?: gives a default value when the left side is null:
fun main() {
val input: String? = null
val name = input ?: "Guest"
println("Hello, $name")
val text: String? = null
val length = text?.length ?: 0
println("Length: $length")
}Output:
Hello, Guest Length: 0
You can also return or throw on the right of ?:, to stop early:
fun greet(name: String?) {
val n = name ?: return
println("Hi, $n")
}
fun main() {
greet("Ravi")
greet(null) // prints nothing
println("Done")
}Output:
Hi, Ravi Done
Not-null assertion: !!
!! tells Kotlin “I’m sure this isn’t null”. If you’re wrong, the program crashes with an NPE:
fun main() {
val a: String? = "Kotlin"
println(a!!.length)
val b: String? = null
try {
println(b!!.length)
} catch (e: NullPointerException) {
println("Crashed: NullPointerException")
}
}Output:
6 Crashed: NullPointerException
Avoid !!. Almost every !! can be replaced with ?., ?: or an if check.
Checking with if (smart cast)
After you check for null, Kotlin treats the variable as non-null inside that block:
fun main() {
val email: String? = "a@b.com"
if (email != null) {
println(email.length) // no ?. needed here
}
}Output:
7
This is called a smart cast. It works for local vals and for vars that can’t change between the check and the use.
let: run code only when not null
fun main() {
val phone: String? = "9876543210"
phone?.let {
println("Sending OTP to $it")
}
val missing: String? = null
missing?.let { println("This won't print") }
println("Done")
}Output:
Sending OTP to 9876543210 Done
Inside let, it is the non-null value. let is one of the scope functions covered in the Functions module.
Safe cast: as?
as? converts to a type, or gives null if it can’t:
fun main() {
val value: Any = "123"
val number: Int? = value as? Int
val text: String? = value as? String
println(number)
println(text)
}Output:
null 123
Nullable collections
fun main() {
val items: List<String?> = listOf("a", null, "b", null)
println(items.filterNotNull())
val maybeList: List<Int>? = null
println(maybeList.orEmpty().size)
}Output:
[a, b] 0
List<String?> is a list that may contain nulls. List<String>? is a list that may itself be null.
Quick reference
| Operator | Meaning | Example |
|---|---|---|
? | type allows null | val s: String? = null |
?. | call only if not null | s?.length |
?: | default if null | s ?: "default" |
!! | assert not null (may crash) | s!!.length |
?.let { } | run a block if not null | s?.let { println(it) } |
as? | safe cast | x as? Int |
Common mistakes
- Using
!!everywhere: it brings back the crashes Kotlin was designed to prevent. - Making everything nullable: use
String?only when null really means something (“not set yet”, “not found”). - Forgetting that
?.returns a nullable value:s?.lengthis anInt?, not anInt. Add?: 0if you need a number.
Exercise
Given a nullable user name and age, print a greeting that falls back to sensible defaults.
fun describe(name: String?, age: Int?): String {
val n = name?.trim()?.takeIf { it.isNotEmpty() } ?: "Guest"
val a = age?.let { "$it years old" } ?: "age unknown"
return "$n, $a"
}
fun main() {
println(describe(" Meera ", 24))
println(describe(null, null))
println(describe(" ", 30))
}Output:
Meera, 24 years old Guest, age unknown Guest, 30 years old
FAQ
What is the Elvis operator in Kotlin?
?: returns the left side if it isn’t null, otherwise the right side: val name = input ?: "Guest".
When should I use !! in Kotlin?
Rarely. Only when a null value would be a genuine bug, and you’d rather crash immediately than continue.
Can Kotlin still throw NullPointerException?
Yes, mainly when you use !! on a null value, or when Java code returns null where Kotlin expected a value. In ordinary Kotlin code, null safety catches the problem at compile time.
