Kotlin Nullable Types — Complete Guide

1. What are Nullable Types in Kotlin?

In Kotlin, nullable types are used to explicitly allow a variable to hold a null value. By default, variables in Kotlin cannot be null. This feature helps prevent NullPointerException (NPE) at runtime.

Example:

// Non-nullable variable
val name: String = "Talha"
// name = null // ❌ Compilation error

// Nullable variable
val nullableName: String? = null
println(nullableName) // Output: null
            

2. How to Work with Nullable Types

Example 1 — Safe Call Operator ?.

val length = nullableName?.length
println(length) // Output: null (instead of throwing NPE)
        
Example 2 — Elvis Operator ?:

val nameLength = nullableName?.length ?: 0
println(nameLength) // Output: 0 if nullableName is null
        
Example 3 — Safe Call with let

nullableName?.let { 
    println("Length is ${it.length}") 
}
// Will only execute if nullableName is not null
        
Example 4 — Not-Null Assertion !!

// Use with caution!
val length2 = nullableName!!.length // Throws NPE if nullableName is null
        
Example 5 — Nullable Collections

val names: List = listOf("Ali", null, "Ahmed")
names.forEach { 
    println(it?.length ?: "No value") 
}
// Prints lengths or "No value" for nulls
        

3. Common Patterns with Nullable Types


4. Top 5 Interview Questions (With Answers)

  1. Q1: What is a nullable type in Kotlin?
    Ans: A variable that can hold null is declared with ?, e.g., String?.
  2. Q2: How do you safely access a nullable variable’s property?
    Ans: Use the safe call operator ?..
  3. Q3: What does the Elvis operator ?: do?
    Ans: It provides a default value if the left-hand side is null.
  4. Q4: When should you use !! in Kotlin?
    Ans: Only when you are certain the variable is not null; otherwise, it throws a NullPointerException.
  5. Q5: Can a list contain nullable elements?
    Ans: Yes, e.g., List can hold null values.
Final Tip 💡

Kotlin’s nullable types are designed to make your code safer. Always prefer ?. and ?: instead of using !!, and leverage let for conditional execution on non-null values.