Variables
7 min · Kotlin
Store values in named boxes called variables.
Enemy 1 of 5
A variable gives a value a name so you can refer to it later instead of retyping it. In Kotlin, the most common way to create one is with val: val name = "Ada" creates a variable called name holding the text "Ada". After that, writing name anywhere means "the value stored in name".
val stands for "value" and creates a read-only reference — once assigned, it can't be reassigned to something else. If you do need a variable whose value can change later, Kotlin also has var (for "variable"), which you'll use starting in the next few lessons when you need to mutate things like a running score or a game state. A widely followed Kotlin habit is to reach for val by default and only use var when you genuinely need to reassign — this mirrors how Rust defaults to immutable let, and for the same reason: fewer moving parts means fewer bugs.
Kotlin figures out the type of a variable from the value you assign, a feature called type inference — you don't need to write val name: String = "Ada" every time, though you can be explicit whenever it improves clarity, especially for public functions or tricky cases.
Loading editor...