Null Safety
Kotlin's signature feature: nullable types, safe calls, and the Elvis operator.
What you'll learn
- Explain why Kotlin distinguishes nullable (String?) from non-nullable (String) types at compile time
- Use the safe-call operator (?.) and the Elvis operator (?:)
- Recognize what the non-null assertion (!!) does and why it should be used sparingly
Explanation
Kotlin's most distinctive feature is built-in null safety. A regular type like String cannot hold null -- the compiler rejects it. To allow null, you must explicitly mark the type nullable with a ?: String?. This turns "forgot to check for null" from a runtime crash (a NullPointerException, notoriously common in Java) into a compile-time error you must address before the code even runs.
The safe-call operator ?. accesses a property or calls a method only if the receiver isn't null, otherwise the whole expression evaluates to null: val length = name?.length -- if name is null, length is null too, with no exception thrown.
The Elvis operator ?: provides a default value when the left side is null: val length = name?.length ?: 0 -- "use name's length, or 0 if name is null."
The non-null assertion !! forces a nullable value to be treated as non-null, throwing a NullPointerException immediately if it actually is null. It exists for cases where you're certain a value can't be null, but using it defeats the purpose of null safety and should be rare -- prefer ?. and ?: wherever possible.
Guided lab
Predict: Safe call and Elvis operator
Read this program and predict exactly what it prints.
fun main() {
val name: String? = null
val otherName: String? = "Grace"
println(name?.length ?: 0)
println(otherName?.length ?: 0)
}Stuck? Get a hint.
Common mistakes
- Overusing `!!` to silence a compiler error instead of genuinely handling the null case with `?.`/`?:` -- this just moves the crash to runtime, defeating the point of null safety.
- Forgetting that a plain `String` (no `?`) genuinely cannot hold null -- the compiler will reject an attempt to assign null to it.
- Assuming `?.` throws on null -- it doesn't; it safely evaluates to null instead.
Knowledge check
Takeaway
Prefer ?. and ?: to safely handle nullable values -- reach for !! only when you're truly certain a value can't be null.
Summary
Kotlin distinguishes nullable (String?) from non-nullable (String) types at compile time; ?. safely accesses, ?: provides a default, and !! asserts non-null (throwing if wrong).
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.