root@coding-prodigies:~# โ–Š
// lesson 3 of 11 ยท 18 min

Null safety

โš‘ Report an issue with this lesson
var title: String = "HTML Fundamentals"  // cannot be null
var subtitle: String? = null               // nullable, marked explicitly

subtitle?.length             // safe call: returns null instead of crashing
subtitle ?: "No subtitle"     // Elvis operator: fallback if null

A plain String can never hold null -- the compiler enforces it. You have to explicitly opt in to nullability with ?, which eliminates most of the null-pointer crashes that plague Java code.

Safe calls chain naturally, short-circuiting to null the moment any link in the chain is null -- no nested if-checks needed:

class Address(val city: String?)
class Student(val address: Address?)

val student: Student? = getStudent()
val city: String? = student?.address?.city
// if student is null, or student.address is null, city is simply null --
// no NullPointerException anywhere in this chain

When you're certain a value isn't actually null despite its type saying it could be, the not-null assertion operator !! forces an unwrap -- but it throws a NullPointerException immediately if you're wrong, so it should be rare in reviewed code:

val subtitle: String? = fetchSubtitle()
val length = subtitle!!.length // crashes here if subtitle is actually null

!! is sometimes called Kotlin's "trust me" operator, and overusing it defeats the entire purpose of null safety -- it just moves the crash from "anywhere" (Java) to "this exact line" (Kotlin), which is an improvement, but ?., ?:, and let almost always express the same intent more safely.

smart casts are another piece of the puzzle: once you've null-checked a variable with a regular if, Kotlin lets you use it as non-null for the rest of that scope without an explicit unwrap:

fun printLength(text: String?) {
    if (text != null) {
        println(text.length) // smart-cast to String, no ?. needed here
    }
}

Smart casts only work on vals (or local variables the compiler can prove aren't reassigned between the check and the use) -- a var property could theoretically be changed by another thread between the check and the use, so Kotlin won't smart-cast those.

Try it yourself

Exercise: Make subtitle nullable and use the Elvis operator to print a fallback if it's null.
Expected output:
No subtitle
kotlin
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

8 more lessons โ€” including Capstone project: a course catalog app โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99