What is Null Safety in Kotlin: Explanation and Examples
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.
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
}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
? to declare a variable that can hold null and handle it safely with operators like ?. and ?:.