Variables, val and var
Variables, val and var
A student’s name can remain fixed while a corrected mark changes. Val prevents reassignment of a binding; var permits it. Kotlin can infer a type from an initial value, so you can often express both the value and its intended mutability without a separate type annotation.
What you’ll learn
- Choose val or var from the required reassignment.
- Distinguish a stable binding from mutable object contents.
Variables, val and var in the example
Score 72
A student’s name can remain fixed while a corrected mark changes.
Score 72Add bonus 8
An assignment stores a value, while equality uses a comparison operator.
Add bonus 8Display 80
Score starts at 72 and the compound assignment stores 80.
Display 80
Understand variables, val and var
An assignment stores a value, while equality uses a comparison operator. Reassigning an Int variable to text is not an automatic conversion. A val reference to a mutable object can still allow operations on that object; preventing reassignment is different from deeply freezing data.
Follow variables, val and var
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun main() {
val name = "Diya"
var score = 72
score += 8
println("$name: $score")
}Expected output
Diya: 80Follow the execution
Score starts at 72 and the compound assignment stores 80. The string template inserts the name and current score. The name is not reassigned, so val describes the intention accurately.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Variables, val and var
Your task: Which binding needs var if the score must be corrected?
Kotlin/JVM · complete program
fun main() {
val name = "Diya"
var score = 72
score += 8
println("$name: $score")
}Worked answer
The score binding needs var. Keep name as val while its reference does not need reassignment; there is no reason to make every binding mutable.
Variables, val and var: the important boundary
Prefer the least mutability the operation needs, but do not confuse val with immutable object contents. A mutable list held by val can still have elements added through its API.
Check your understanding
Variables, val and var: what to keep in mind
The score binding needs var. Keep name as val while its reference does not need reassignment; there is no reason to make every binding mutable. Prefer the least mutability the operation needs, but do not confuse val with immutable object contents.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.