0
0
Kotlinprogramming~5 mins

Nullable types with ? suffix in Kotlin

Choose your learning style9 modes available
Introduction

Nullable types let you say a variable can hold a value or be empty (null). This helps avoid errors when something might be missing.

When a user might not enter a value and you want to allow empty input.
When reading data from a database that might have missing fields.
When a function can return a value or nothing (null).
When you want to safely check if a variable has a value before using it.
Syntax
Kotlin
var name: String? = null
val age: Int? = 25

The ? after the type means the variable can be null.

Without ?, the variable cannot be null and must always have a value.

Examples
This variable can hold a string or be null.
Kotlin
var message: String? = "Hello"
message = null
Both variables can hold an integer or null.
Kotlin
val number: Int? = 10
val emptyNumber: Int? = null
Without ?, null is not allowed.
Kotlin
var text: String = "Hi"
// text = null // This will cause an error
Sample Program

This program shows a nullable string variable. It prints the name, sets it to null, then safely tries to get its length without crashing.

Kotlin
fun main() {
    var name: String? = "Alice"
    println("Name: $name")
    name = null
    println("Name after null: $name")

    // Safe call to avoid error when name is null
    println("Name length: ${name?.length}")
}
OutputSuccess
Important Notes

Use the safe call operator ?. to access properties or methods safely on nullable variables.

Trying to use a nullable variable without checking can cause errors.

Summary

Adding ? after a type means the variable can be null.

Nullable types help prevent crashes by forcing you to handle empty values.

Use safe calls ?. to work with nullable variables safely.