Kotlin Academy · Lesson

Nullable Types and the ? Modifier

Declare nullable variables and understand Kotlin's null safety at compile time.

Lesson 1 of 413 steps

Nullable Types and the ? Modifier is a free Kotlin Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

Null Safety in Kotlin

Kotlin distinguishes between types that can hold null and those that cannot — at compile time. The compiler stops most NullPointerExceptions before runtime.

Non-Null Type

By default, a Kotlin type cannot be null. Try to assign null and the compiler refuses.

fun main() {
    val name: String = "Ada"
    // val nope: String = null // ERROR
    println(name)
}

Nullable Type with ?

Append ? to allow null. The compiler now treats the variable as optionally absent.

fun main() {
    val name: String? = null
    println(name) // null
}

Calling Methods on Nullables

You cannot call a method directly on a nullable without first handling the null case. The compiler refuses.

fun main() {
    val name: String? = "Bob"
    // println(name.length) // ERROR — name might be null
    if (name != null) println(name.length) // smart cast
}

Smart Casts

After an if (x != null) check, Kotlin smart-casts x to non-null inside the branch.

fun main() {
    val name: String? = "Alice"
    if (name != null) {
        println("Length: ${name.length}") // safe, smart-cast
    } else {
        println("No name")
    }
}

Nullable Function Parameter

Mark function parameters nullable when they might be missing. The caller has to provide a value or null explicitly.

fun greet(name: String?) {
    if (name == null) println("Hello, stranger")
    else println("Hello, $name")
}
fun main() {
    greet("Sara")
    greet(null)
}

Nullable Return Type

A function returning X? tells the caller it might return null — they must handle it.

fun findUser(id: Int): String? {
    return if (id == 1) "Alice" else null
}
fun main() {
    val u = findUser(2)
    println(u ?: "no user")
}

Nullable Properties

Class properties can be nullable too. Common when fields are populated later or fetched optionally.

data class Profile(
    val name: String,
    val avatarUrl: String?
)
fun main() {
    val p = Profile("Lee", null)
    println(p.avatarUrl ?: "(no avatar)")
}

Nullable Collections

Distinguish a nullable list List<T>? from a list of nullables List<T?>. They mean different things.

fun main() {
    val maybeList: List<Int>? = null
    val listOfMaybe: List<Int?> = listOf(1, null, 3)
    println(maybeList?.size)     // null
    println(listOfMaybe.size)    // 3
}

Comparison with Java

Java types crossing into Kotlin appear as platform types (String!) — Kotlin trusts you but offers no null safety. Always annotate Java APIs with @Nullable/@NotNull when possible.

fun main() {
    val maybeNull: String? = System.getenv("FOO") // null if unset
    println("env FOO = ${maybeNull ?: "(unset)"}")
}

Why It Matters

Compile-time null safety prevents an entire class of runtime crashes. Embrace the ? modifier — it documents intent and forces handling.

fun divide(a: Int, b: Int): Int? = if (b == 0) null else a / b
fun main() {
    val r1 = divide(10, 2) // 5
    val r2 = divide(10, 0) // null — handled at call site
    println("$r1, $r2")
}

Quick Check

What does the ? at the end of a type declaration mean?

Recap

By default, Kotlin types are non-nullable. Add ? to opt in to null. The compiler enforces null handling via smart casts, safe calls, and the Elvis operator — preventing most NullPointerExceptions before runtime.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Nullable Types and the ? Modifier” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “Nullable Types and the ? Modifier”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “Nullable Types and the ? Modifier”?

Declare nullable variables and understand Kotlin's null safety at compile time. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Nullable Types and the ? Modifier” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Nullable Types and the ? Modifier
  2. Safe Call ?. and Elvis ?: in Real Code
  3. let, also, and run with Nullable Receivers
  4. !! Operator: When and Why to Avoid It
← Back to Kotlin Academy