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 = 30Kotlin has mainly three ways to store values:
| Keyword | Meaning |
|---|---|
val | Fixed value |
var | Changeable value |
const val | Fixed compile-time constant |
2. val
What is val?
val means the value cannot be reassigned.
fun main() {
val name = "Mahesh"
println(name)
}Output
MaheshYou cannot change val again.
fun main() {
val name = "Mahesh"
// name = "Rahul" // Error
}Use val When
| Use Case | Example |
|---|---|
| Fixed user name | val userName = "Mahesh" |
| Fixed title | val title = "Home" |
| API response object | val user = User() |
| Calculation result | val 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
31Use var When
| Use Case | Example |
|---|---|
| Counter | var count = 0 |
| Score | var score = 10 |
| Login status | var isLoggedIn = false |
| Cart item count | var cartCount = 0 |
Example: Cart Count
fun main() {
var cartCount = 0
cartCount = cartCount + 1
cartCount = cartCount + 1
println("Cart count: $cartCount")
}Output
Cart count: 24. 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 AppCommon Use Cases
const val BASE_URL = "https://api.example.com/"
const val DATABASE_NAME = "student_db"
const val APP_VERSION = "1.0"Important Rules
| Rule | Explanation |
|---|---|
const val cannot be inside function | It must be top-level or inside companion object |
| Value must be known before runtime | Example: "MyApp" is allowed |
| Runtime value is not allowed | Example: 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
| Keyword | Can Change? | Where Used? | Example |
|---|---|---|---|
val | No | Inside function/class | val name = "Mahesh" |
var | Yes | Inside function/class | var count = 0 |
const val | No | Top-level/companion object | const val BASE_URL = "..." |
Diagram