📦 Kotlin – Variables: Understanding val vs var in Kotlin
🧲 Introduction – Why Learn Kotlin Variables First?
Variables are the building blocks of every program. In Kotlin, you define variables using either val or var, which controls whether the variable is immutable (read-only) or mutable (changeable). Mastering Kotlin’s variable declarations helps you write safer, cleaner, and more maintainable code.
🎯 In this guide, you’ll learn:
- How to declare variables in Kotlin using
valandvar - The difference between mutable and immutable variables
- Type inference and explicit typing
- Common mistakes and best practices
🔑 Kotlin Variable Declaration Syntax
val name = "Kotlin"
var age = 25
| Keyword | Description |
|---|---|
val | Immutable (read-only) variable |
var | Mutable (changeable) variable |
✅ Kotlin automatically detects the variable type using type inference.
🔐 val – Immutable Variable
Use val when the value won’t change after assignment.
val pi = 3.1416
println("Value of pi is $pi")
Attempting to reassign will cause a compile-time error:
pi = 3.14 // ❌ Error: Val cannot be reassigned
✅ Great for constants, configurations, final values.
🔁 var – Mutable Variable
Use var when the value can change during execution.
var counter = 0
counter += 1
println("Counter: $counter")
✅ Useful for loop counters, user inputs, or state changes.
🧠 Kotlin Type Inference vs Explicit Typing
✅ Type Inference (Recommended):
val city = "Paris" // Inferred as String
var score = 95 // Inferred as Int
✅ Explicit Typing (Optional):
val country: String = "India"
var temperature: Double = 36.6
📌 Use explicit types when:
- You want code clarity
- Working with complex objects
- Interfacing with Java or APIs
🧪 Reassigning vs Rebinding in Kotlin
val list = mutableListOf(1, 2, 3)
list.add(4) // ✅ Allowed: modifying object content
// list = mutableListOf(5, 6) ❌ Not allowed: rebinding the reference
📍 val prevents reassigning the reference, not the mutable object content.
🧾 Kotlin Variable Declaration Examples
| Example | Result |
|---|---|
val language = "Kotlin" | Immutable string |
var year = 2025 | Mutable integer |
val isLoggedIn = true | Boolean value |
var grade: Char = 'A' | Character with explicit type |
val result = 4 + 5 | Type inferred as Int (value 9) |
🧪 Kotlin Smart Casts with val
Since val values don’t change, Kotlin can automatically smart-cast them:
fun printLength(str: Any) {
if (str is String) {
println(str.length) // No explicit cast needed
}
}
🔎 This would not be possible with var in all cases, since the value could change.
🚫 Common Mistakes with Kotlin Variables
| ❌ Mistake | ✅ Fix |
|---|---|
Reassigning a val | Use var if reassignment is needed |
Using var unnecessarily | Use val by default, var only if needed |
| Not initializing a variable | Provide a value or use lateinit/nullable |
✅ Best Practices for Kotlin Variables
| Practice | Reason |
|---|---|
Prefer val over var | Encourages immutability and thread safety |
Use descriptive names (totalAmount) | Improves code readability |
| Use explicit types in APIs or models | Increases clarity and maintainability |
| Avoid shadowing variable names | Prevents confusion and bugs |
📌 Summary – Recap & Next Steps
Kotlin variables use val and var to balance between safety and flexibility. Use val for immutable values and var for mutable ones. Kotlin’s smart type inference makes declarations clean and concise, while still being type-safe.
🔍 Key Takeaways:
valcreates a read-only variable;varallows reassignment.- Kotlin infers types, but you can declare them explicitly.
- Use
valby default unless mutation is necessary. - Modifying an object referenced by
valis allowed; reassignment is not.
⚙️ Practical Use:
Choosing between val and var helps create predictable, bug-resistant code—essential for Android apps, backend services, and data modeling.
❓ FAQs – Kotlin Variables
❓ What’s the difference between val and var in Kotlin?
✅ val is for immutable variables (cannot be reassigned), while var is mutable (can be changed).
❓ Can I change the contents of a list declared with val?
✅ Yes, you can modify the contents of a mutable object. You just can’t reassign the reference itself.
❓ Is Kotlin strictly typed even with inferred variables?
✅ Yes. Even if Kotlin infers the type, it remains a statically typed language.
❓ When should I use explicit types in Kotlin?
✅ Use them when clarity is needed, especially in public APIs, shared models, or generics.
❓ Can I declare an uninitialized val?
✅ Only if it’s declared inside a class as a lateinit var or as a custom getter with no initial value.
Share Now :
