What is null safety in Kotlin?
Null safety in Kotlin is a feature that helps prevent errors caused by null values.
In many languages like Java, accessing a null value causes a runtime crash. Kotlin avoids this by handling nulls at compile time.
Kotlin forces you to explicitly decide whether a variable can be null or not — reducing unexpected crashes.
Nullable vs Non-nullable types
In Kotlin, variables are non-nullable by default. This means they cannot hold null unless you explicitly allow it.
var name: String = "John" name = null // ❌ Error
To allow null values, you must use the ? symbol:
var name: String? = "John" name = null // ✅ Allowed
Safe call operator (?.)
The safe call operator ?. allows you to access properties safely without crashing.
val name: String? = null println(name?.length) // prints null instead of crashing
Elvis operator (?:)
The Elvis operator provides a default value when something is null.
val name: String? = null val length = name?.length ?: 0 println(length) // 0
Not-null assertion (!!)
The !! operator forces Kotlin to treat a value as non-null. If it is null, your app will crash.
val name: String? = "Kotlin" println(name!!.length) // use carefully
Why null safety matters
- 🛡️ Prevents NullPointerException crashes
- ⚙️ Forces safer code design
- 📘 Improves readability and clarity
- 🚀 Reduces runtime bugs
- 👥 Helps large teams avoid hidden errors
Null pointer exceptions are one of the most common crash reasons in Java apps. Kotlin was designed specifically to eliminate this class of bugs.
Summary
Null safety in Kotlin ensures that null values are handled explicitly and safely.
With nullable types, safe calls, and operators like ?:, Kotlin prevents many common runtime crashes.
In short: Kotlin makes null errors a compile-time problem instead of a runtime disaster.