What if you could stop accidental changes in your code before they even happen?
Why Properties with val and var in Kotlin? - Purpose & Use Cases
Imagine you have a notebook where you write down your daily tasks. Sometimes you want to keep a task as it is, and other times you want to be able to change it later. Without a clear way to mark which tasks can be changed and which cannot, you might accidentally erase or alter important notes.
Manually tracking which values should stay fixed and which can change is confusing and error-prone. You might overwrite important data by mistake or waste time checking if a value should be updated. This slows down your work and causes bugs.
Kotlin's val and var keywords let you clearly mark properties as read-only or mutable. This way, the compiler helps you avoid accidental changes and makes your code safer and easier to understand.
class Task { var description: String = "" fun updateDescription(newDesc: String) { description = newDesc } }
class Task(val id: Int, var description: String)This lets you write safer and clearer code by explicitly controlling which properties can change and which cannot.
Think of a bank account number that should never change once set (val), versus the account balance that updates with each transaction (var).
val creates read-only properties that cannot be changed after assignment.
var creates mutable properties that can be updated anytime.
Using them properly prevents bugs and makes your code easier to read.
Practice
val and var properties in Kotlin?Solution
Step 1: Understand
valbehaviorvalproperties are assigned once and cannot be reassigned later.Step 2: Understand
varbehaviorvarproperties can be reassigned multiple times after initialization.Final Answer:
valis read-only after initialization,varcan be changed anytime. -> Option BQuick Check:
val= read-only,var= mutable [OK]
- Confusing val as mutable
- Thinking var is read-only
- Believing val and var behave the same
age of type Int in Kotlin?Solution
Step 1: Identify mutable property keyword
Mutable properties usevarkeyword.Step 2: Check initialization
Property must be initialized or declared nullable; hereageis initialized with 25.Final Answer:
var age: Int = 25 -> Option AQuick Check:
Mutable property usesvar[OK]
- Using val for mutable property
- Not initializing non-nullable property
- Omitting type without initialization
class Person {
val name = "Anna"
var age = 30
}
fun main() {
val p = Person()
println(p.name)
p.age = 31
println(p.age)
}Solution
Step 1: Check
val nameusagenameis aval, so it prints "Anna" and cannot be changed.Step 2: Check
var agereassignmentageis avar, so it can be changed from 30 to 31 before printing.Final Answer:
Anna 31 -> Option DQuick Check:
valprints original,varprints updated [OK]
- Expecting error on changing var
- Thinking val can be reassigned
- Confusing printed values
class Car {
val model: String
var year: Int
init {
model = "Tesla"
year = 2020
}
}
fun main() {
val car = Car()
car.model = "BMW"
println(car.model)
}Solution
Step 1: Check
val modelreassignmentmodelis declared asval, so it cannot be reassigned after initialization.Step 2: Verify property initialization
modelandyearare both initialized ininit, so no initialization error.Final Answer:
Cannot assign a new value to val property 'model'. -> Option AQuick Check:
val properties cannot be reassigned [OK]
- Trying to reassign val property
- Ignoring uninitialized var warnings
- Assuming val can be reassigned
Book where the title should never change after creation, but the price can be updated. Which declaration is correct?Solution
Step 1: Determine immutability for
titletitleshould not change, so declare it withval.Step 2: Determine mutability for
pricepricecan change, so declare it withvar.Final Answer:
class Book(val title: String, var price: Double) -> Option CQuick Check:
Immutable title = val, mutable price = var [OK]
- Using var for title which should be fixed
- Using val for price which should be changeable
- Mixing up val and var keywords
Ready to prove it?
Pass the test and this pattern moves unknown
