0
0
KotlinConceptBeginner · 3 min read

What is Null Safety in Kotlin: Explanation and Examples

Null safety in Kotlin is a feature that helps prevent errors caused by null values by distinguishing nullable and non-nullable types at compile time. It forces developers to explicitly handle null cases, reducing runtime crashes due to null pointer exceptions.
⚙️

How It Works

Imagine you have a box that can either contain something or be empty. In Kotlin, variables are like these boxes. By default, Kotlin boxes cannot be empty (null). If you want a box that can be empty, you have to say so explicitly by adding a ? after the type.

This system helps the compiler check your code before it runs. It warns you if you try to use a box that might be empty without checking first. This way, Kotlin helps you avoid the common problem of trying to use something that isn’t there, which causes crashes.

💻

Example

This example shows how Kotlin forces you to handle null values safely.

kotlin
fun main() {
    var name: String = "Alice"  // Non-nullable
    // name = null  // This would cause a compile error

    var nullableName: String? = "Bob"  // Nullable
    nullableName = null  // Allowed

    // Safe call operator ?. lets you access properties safely
    println(nullableName?.length)  // Prints: null

    // Elvis operator ?: provides a default value if null
    val length = nullableName?.length ?: 0
    println(length)  // Prints: 0
}
Output
null 0
🎯

When to Use

Use null safety in Kotlin whenever you work with variables that might not have a value yet or can be empty. For example, user input, data from a database, or responses from a web service can be null. Kotlin’s null safety forces you to think about these cases and handle them explicitly, making your app more stable and less likely to crash.

It is especially useful in Android development and backend services where null pointer exceptions are common bugs. By using Kotlin’s null safety, you write safer code that clearly shows where nulls are possible and how they are handled.

Key Points

  • Kotlin distinguishes between nullable and non-nullable types using ?.
  • Non-nullable types cannot hold null, preventing many runtime errors.
  • Nullable types require safe calls (?.) or explicit checks before use.
  • Operators like Elvis (?:) help provide default values when null occurs.
  • Null safety improves code reliability and reduces crashes from null pointer exceptions.

Key Takeaways

Kotlin’s null safety prevents null pointer errors by distinguishing nullable and non-nullable types.
Use ? to declare a variable that can hold null and handle it safely with operators like ?. and ?:.
Non-nullable types cannot be assigned null, so the compiler catches mistakes early.
Null safety is essential for writing stable and crash-free Kotlin applications.
Always handle nullable variables explicitly to avoid runtime exceptions.