Beginner: Kotlin · Null safety, functions and lambdas · topic 5 of 50 · 30 min
Null safety
Explanation
The billion-dollar mistake
null means "no value here". In Java and many other languages, any object variable can secretly be null, and calling a method on it crashes the program with a NullPointerException (NPE). For years this was the most common crash in Android apps. Tony Hoare, who invented the null reference in 1965, later called it his "billion-dollar mistake".
Nullable and non-nullable types
Kotlin splits every type in two. String means "always a real string". String? (with a question mark) means "a string or null". The compiler tracks the difference and will not let you use a String? as if it were a String.
fun main() {
val name: String = "Asha"
// val bad: String = null // error: Null can not be a value of a non-null type String
val nickname: String? = null // fine: the ? allows null
println(name.length) // 4
// println(nickname.length) // error: only safe (?.) or non-null asserted (!!.) calls are allowed
}Safe call: ?.
The safe call operator ?. calls a method or reads a property only if the value is not null. If it is null, the whole expression simply becomes null instead of crashing.
val nickname: String? = null
println(nickname?.length) // null
val city: String? = "Mysuru"
println(city?.uppercase()) // MYSURUElvis operator: ?:
The Elvis operator ?: gives a default value when the left side is null. (Turn it sideways and it looks like Elvis Presley's hair.)
val nickname: String? = null
val shown = nickname ?: "Guest"
println("Hello, $shown") // Hello, Guest
val len = nickname?.length ?: 0 // 0Smart casts after a check
fun greet(name: String?) {
if (name != null) {
println(name.length) // name is smart-cast to String here
} else {
println("No name")
}
}let: run code only when not null
val phone: String? = "9876543210"
phone?.let {
println("Sending OTP to $it") // runs only if phone is not null
}The !! operator
!! (the not-null assertion) tells the compiler "trust me, this is not null". If you are wrong, the app crashes with a NullPointerException, exactly what null safety was meant to prevent. Use it almost never; prefer ?., ?: or an if check.
Common mistakes
- Sprinkling !! to silence errors. Each one is a possible crash.
- Making every variable nullable "just in case". Use non-null types wherever a value must exist; nullability should mean something.
- Forgetting that ?. returns a nullable result: nickname?.length is Int?, not Int. Add ?: to get a plain Int.
- Trusting values from Java libraries or JSON to never be null.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Null safety · 1/7
Null means no value. In many languages, using a null by mistake crashes the app.
Prefer a video by a teacher? Find free videos on “kotlin null safety safe call elvis operator tutorial” on YouTube ↗
In real life: An optional referral code at signup
A payments app lets new users enter a referral code, but most leave it empty. The code is stored as String?. When the signup is processed, the app uses referral?.trim()?.uppercase() to clean it only if it exists, and ?: "NONE" for reports. There is no way for an empty referral field to crash the signup.
fun main() {
val referral: String? = null
val code = referral?.trim()?.uppercase() ?: "NONE"
println("Referral: $code") // Referral: NONE
}Practice (0/3 done)
What does this print? val a: String? = null println(a?.length ?: -1)
Which line does NOT compile?
Write fun formatPhone(input: String?): String that returns "Not given" for null or blank input, otherwise the trimmed number with "+91 " in front. Use ?. and ?: (and isNullOrBlank()). Test with null, " ", and " 9876543210 ".
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- FunctionsNull safety, functions and lambdas · same module
- Lambdas and higher-order functionsNull safety, functions and lambdas · same module
- Extension functions and scope functionsNull safety, functions and lambdas · same module
- null, nullable types and null-safe operatorsC# and .NET · Arrays, strings and null
- Sound null safetyFlutter and Dart · Null safety and object-oriented Dart
- Enums and OptionRust Programming · Structs, enums and pattern matching
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does the ? in Int? mean?
Answer: The variable may hold null
A trailing ? marks a nullable type.
What does x ?: 0 return when x is null?
Answer: 0
Elvis returns the right side when the left is null.
What happens with value!! when value is null?
Answer: It throws a NullPointerException
!! asserts non-null and crashes if wrong.
What is the type of name?.length when name is String??
Answer: Int?
A safe call can produce null, so the result is nullable.
With nullable reference types enabled, what does string? mean?Related
Answer: A string that may be null
The ? marks that null is an allowed value.
What is "sound" null safety?Related
Answer: If a type is non-nullable, the value can never be null at run time
The guarantee is enforced by the compiler.
From Sound null safety
Why is Option safer than null?Related
Answer: Only Option types can be missing, and the compiler makes you handle None
Absence is visible in the type and must be handled.
From Enums and Option
Which Kotlin feature should you avoid because it can throw a NullPointerException?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Null safety, functions and lambdas” before its exam: Functions, Lambdas and higher-order functions, Extension functions and scope functions.
- Module 2 exam: Null safety, functions and lambdas · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Classes, objects and collections. 50 topics left in the course before the final exam.