0
0
Kotlinprogramming~5 mins

Non-nullable types by default in Kotlin

Choose your learning style9 modes available
Introduction

Kotlin makes variables non-nullable by default to help you avoid errors caused by missing values. This means you must explicitly say if a variable can be null.

When you want to make sure a variable always has a value and never causes a crash.
When you want to write safer code that avoids unexpected null errors.
When you want to clearly show which variables can be empty and which cannot.
When you are working with data that must always be present, like user names or IDs.
Syntax
Kotlin
val name: String = "Alice"
val age: Int = 30

// To allow null, add a question mark
val nickname: String? = null

By default, types like String and Int cannot hold null.

To allow a variable to be null, add ? after the type.

Examples
This variable city cannot be null. It must always hold a string.
Kotlin
val city: String = "Paris"
This variable country can be null or hold a string.
Kotlin
val country: String? = null
Integer score cannot be null unless declared with Int?.
Kotlin
var score: Int = 100
// score = null // This will cause an error
Here, points can start as null and later hold a number.
Kotlin
var points: Int? = null
points = 50
Sample Program

This program shows a non-nullable name and a nullable nickname. It prints the name and checks if the nickname exists before printing.

Kotlin
fun main() {
    val name: String = "Bob"
    // val nickname: String = null // This line would cause an error
    val nickname: String? = null

    println("Name: $name")
    if (nickname != null) {
        println("Nickname: $nickname")
    } else {
        println("No nickname provided")
    }
}
OutputSuccess
Important Notes

Trying to assign null to a non-nullable variable causes a compile error.

Use nullable types carefully and check for null before using them.

Kotlin's default non-null helps prevent many common bugs related to missing values.

Summary

Kotlin variables are non-nullable by default to keep your code safe.

Add ? after a type to allow null values.

Always check nullable variables for null before using them.