Kotlin Variables
A variable is a named stored value in a program. Kotlin uses val for a value that cannot change and var for a value that can change.
A val value shown
val gives days the value 7. println shows the stored number.
fun main() {
val days = 7
println(days)
}Changing a var
The two println lines show count before and after the change. The count grows from 1 to 2 in the output.
fun main() {
var count = 1
println(count)
count = 2
println(count)
}Two variables in one program
Each name holds its own value. Each println shows one stored value on its own line.
fun main() {
val score = 10
var level = 1
println(score)
println(level)
}Changing a val fails
The last line tries to give limit a new value. The compiler stops and names val in its error.
fun main() {
val limit = 5
limit = 6
}Example
fun main() {
var score = 10
println(score)
score = 15
println(score)
}Key points
- val: a keyword that names a value that cannot change.
- var: a keyword that names a value that can change.
- Use = to give a name its value.
- Use a name in println to show the value it holds.
- Names in this course start with a letter.
In this example, var score starts with the value 10. The first println shows 10. The next line changes score to 15. The last println shows 15.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
Which keyword names a value that can change?