Read-Only Variables
So far, you have seen variables whose values can be reassigned – also known as mutable variables. But often, you will want to use variables whose values should not change. For example, in the text adventure game, the player’s name will not change after it has been initially assigned.
Kotlin provides a different syntax for declaring read-only variables – variables that cannot be modified once they are assigned.
You declare a variable that can be modified using the var
keyword.
To declare a read-only variable, you use the val
keyword.
Colloquially, variables whose values can change are referred to as var
s and read-only variables are referred to as val
s.
We will follow this convention from now on, because “variable ...
Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.