Read-Only Variables
So far, you have seen variables whose values can be reassigned. But often, you will want to use variables whose values should not change in your program. 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, since “variable” and “read-only ...
Get Kotlin Programming: The Big Nerd Ranch Guide, First 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.