Kotlin Null Safety


Kotlin Null Safety – Explained Simply & Uniquely

In Kotlin, null safety is a smart feature that helps avoid unexpected crashes from accessing non-existent values (a common issue in many languages like Java).


What is Null?

  • null means nothing or no value.
  • Trying to use a null value without checking causes errors.

Declaring Nullable Types

By default, variables can’t be null in Kotlin.

To allow it, use a ? after the type:

var name: String? = null  // This is allowed

Accessing Nullable Variables

You can't directly use nullable variables like non-null ones. Use safe calls:

println(name?.length)  // Prints length if name is not null 

The Elvis Operator ?:

Set a fallback value when a variable is null:

val length = name?.length ?: 0  // Uses 0 if name is null 

Not-Null Assertion !!

Force Kotlin to treat a nullable as non-null (risky!):

val length = name!!.length  // Crashes if name is null 

Use it only when you're 100% sure the value isn’t null.


Safe Functions with Nullable Parameters

You can build functions that take or return nullable types:

fun greet(user: String?): String {    
     return "Hello, ${user ?: "Guest"}" 
} 

Summary:

Kotlin guards your code from null-pointer issues by requiring you to clearly handle missing data. This makes your programs more stable and easier to trust.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand KOTLIN Tutorial visually:

What You'll Learn:
  • 📌 #13 Kotlin Tutorial | Null Handling
  • 📌 Kotlin NULL Safe Operators | Best Explanation Ever | Elvis Operator and Non Null Assertion Operators
Previous Next