Careeroza
val vs var
Declaring Variables
Kotlin has two keywords for variables:
val(value) — read-only. Assigned once, cannot be reassigned. Likefinalin Java.var(variable) — mutable. Can be reassigned later.
Example
Use val for things that do not change and var for things that do.
fun main() {
val name = "Asha" // never changes
var cartItems = 2 // changes as the user shops
println("$name has $cartItems items")
cartItems = 3
cartItems += 1
println("$name now has $cartItems items")
}Output
Asha has 2 items Asha now has 4 items
Reassigning a val is an Error
val city = "Pune"
city = "Mumbai" // ERROR: Val cannot be reassignedTip: Rule of thumb used by Android and backend teams: always start with val. Change it to var only when you really need to reassign. Fewer changing values means fewer bugs.
Declare Now, Assign Later
Example
A val can be declared first and assigned exactly once later, as long as the compiler can see it is assigned before use.
fun main() {
val discount: Int
val isPrimeMember = true
if (isPrimeMember) {
discount = 20
} else {
discount = 0
}
println("Discount: $discount%")
}Output
Discount: 20%