Here we learn about kotlin variable declaration rules for var, val and const val

1. Variables in Kotlin

A variable is used to store data.

Example:

val name = "Mahesh"
var age = 30

Kotlin has mainly three ways to store values:

KeywordMeaning
valFixed value
varChangeable value
const valFixed compile-time constant


2. val

What is val?

val means the value cannot be reassigned.

fun main() {
    val name = "Mahesh"
    println(name)
}

Output

Mahesh

You cannot change val again.

fun main() {
    val name = "Mahesh"
    // name = "Rahul" // Error
}

Use val When

Use CaseExample
Fixed user nameval userName = "Mahesh"
Fixed titleval title = "Home"
API response objectval user = User()
Calculation resultval total = price + tax


3. var

What is var?

var means the value can be changed.

fun main() {
    var age = 30
    age = 31

    println(age)
}

Output

31

Use var When

Use CaseExample
Countervar count = 0
Scorevar score = 10
Login statusvar isLoggedIn = false
Cart item countvar cartCount = 0


Example: Cart Count

fun main() {
    var cartCount = 0

    cartCount = cartCount + 1
    cartCount = cartCount + 1

    println("Cart count: $cartCount")
}

Output

Cart count: 2


4. const val

What is const val?

const val is used for values that are fixed before the program runs.

It is called a compile-time constant.

Example:

const val APP_NAME = "Kotlin Learning App"

fun main() {
    println(APP_NAME)
}

Output

Kotlin Learning App


Common Use Cases

const val BASE_URL = "https://api.example.com/"
const val DATABASE_NAME = "student_db"
const val APP_VERSION = "1.0"


Important Rules

RuleExplanation
const val cannot be inside functionIt must be top-level or inside companion object
Value must be known before runtimeExample: "MyApp" is allowed
Runtime value is not allowedExample: current time is not allowed


Wrong Example

fun main() {
    // const val APP_NAME = "MyApp" // Error
}


Correct Example

const val APP_NAME = "MyApp"

fun main() {
    println(APP_NAME)
}


5. val vs var vs const val

KeywordCan Change?Where Used?Example
valNoInside function/classval name = "Mahesh"
varYesInside function/classvar count = 0
const valNoTop-level/companion objectconst val BASE_URL = "..."


Diagram