0
0
Kotlinprogramming~5 mins

Why null safety is Kotlin's defining feature

Choose your learning style9 modes available
Introduction

Null safety helps prevent errors when a program tries to use something that is missing or empty. Kotlin makes this easy and safe by design.

When you want to avoid crashes caused by missing values in your app.
When you need to clearly show if a variable can be empty or must always have a value.
When you want your code to be easier to read and safer to run.
When working with data from users or external sources that might be missing.
When you want to catch mistakes early while writing code instead of during app use.
Syntax
Kotlin
var name: String = "John"  // cannot be null
var nickname: String? = null  // can be null

Use ? after the type to allow a variable to hold null.

Without ?, Kotlin will not allow null values, preventing errors.

Examples
This shows that a normal String cannot be set to null.
Kotlin
var message: String = "Hello"
message = null  // Error: Null can not be a value of a non-null type String
Adding ? allows the variable to hold null safely.
Kotlin
var message: String? = "Hello"
message = null  // This is allowed
Use ?. to safely access properties when the variable might be null.
Kotlin
val length = message?.length  // Safe call operator returns length or null
Use !! to assert a variable is not null, but it can crash if wrong.
Kotlin
val length = message!!.length  // Throws error if message is null
Sample Program

This program shows how Kotlin handles null safety. It prints the length of a non-null name, then safely tries to print the length of a nullable nickname which starts as null, then changes to a value.

Kotlin
fun main() {
    var name: String = "Alice"
    println("Name length: ${name.length}")

    var nickname: String? = null
    println("Nickname length: ${nickname?.length}")

    nickname = "Ally"
    println("Nickname length: ${nickname?.length}")
}
OutputSuccess
Important Notes

Null safety helps avoid the common 'null pointer exception' errors found in many languages.

Using ? and safe calls ?. makes your code more reliable and easier to maintain.

Be careful with !! because it can cause crashes if the value is actually null.

Summary

Kotlin's null safety prevents many common bugs by making null explicit.

Use ? to allow nulls and safe calls ?. to handle them safely.

This feature makes Kotlin code safer and easier to understand.