0
0
KotlinHow-ToBeginner · 3 min read

How to Check if Variable is Null in Kotlin: Simple Guide

In Kotlin, you can check if a variable is null by using the equality operator == null or the safe call operator ?.. For example, if (variable == null) checks if the variable is null safely and clearly.
📐

Syntax

To check if a variable is null in Kotlin, use the equality operator == null. You can also use the safe call operator ?. to safely access properties or methods only if the variable is not null.

  • variable == null: Returns true if variable is null.
  • variable != null: Returns true if variable is not null.
  • variable?.property: Accesses property only if variable is not null, otherwise returns null.
kotlin
val variable: String? = null

if (variable == null) {
    println("Variable is null")
} else {
    println("Variable is not null")
}
Output
Variable is null
💻

Example

This example shows how to check if a nullable string variable is null and how to safely access its length using the safe call operator.

kotlin
fun main() {
    val name: String? = null

    if (name == null) {
        println("Name is null")
    } else {
        println("Name length: ${name.length}")
    }

    // Using safe call operator
    println("Name length using safe call: ${name?.length}")
}
Output
Name is null Name length using safe call: null
⚠️

Common Pitfalls

One common mistake is trying to access properties or methods on a nullable variable without checking for null, which causes a compile-time error in Kotlin. Another mistake is using === null which checks for reference equality but == null is preferred for null checks.

Always use == null or safe calls ?. to avoid errors.

kotlin
fun main() {
    val text: String? = null

    // Wrong: causes compile error
    // println(text.length)

    // Right: check null before access
    if (text != null) {
        println(text.length)
    } else {
        println("Text is null")
    }

    // Using safe call
    println(text?.length)
}
Output
Text is null null
📊

Quick Reference

Check TypeSyntaxDescription
Check if nullvariable == nullReturns true if variable is null
Check if not nullvariable != nullReturns true if variable is not null
Safe callvariable?.propertyAccess property only if variable is not null
Elvis operatorvariable ?: defaultValueReturns variable if not null, else defaultValue

Key Takeaways

Use 'variable == null' to check if a variable is null in Kotlin.
Use safe call operator '?.' to safely access properties or methods on nullable variables.
Avoid accessing nullable variables directly without null checks to prevent errors.
Use 'variable ?: defaultValue' to provide a default when variable is null.
Prefer '==' over '===' for null checks in Kotlin.