0
0
Kotlinprogramming~5 mins

Var for mutable references in Kotlin

Choose your learning style9 modes available
Introduction

Use var when you want to change the value of a variable later. It lets you keep a box where you can put different things over time.

When you want to keep track of a score that changes during a game.
When you need to update a user's name after they edit it.
When counting how many times a button is clicked.
When storing a temperature that updates every hour.
When you want to change a setting value based on user input.
Syntax
Kotlin
var variableName: Type = initialValue

var means the variable can change.

You must give it a type or let Kotlin figure it out from the initial value.

Examples
This creates a variable age that can change and starts at 25.
Kotlin
var age: Int = 25
Kotlin figures out name is a String from the value "Alice".
Kotlin
var name = "Alice"
You can declare first and assign later.
Kotlin
var temperature: Double
temperature = 36.6
Sample Program

This program shows how a var variable counter changes its value step by step.

Kotlin
fun main() {
    var counter = 0
    println("Counter starts at: $counter")
    counter = 5
    println("Counter changed to: $counter")
    counter += 10
    println("Counter after adding 10: $counter")
}
OutputSuccess
Important Notes

Use var only when you need to change the value. Otherwise, use val for fixed values.

Changing a var variable means you can update your program's data as things happen.

Summary

var creates a variable that can change its value.

It is useful when you want to update information during your program.

Always give it a starting value or type so Kotlin knows what it holds.