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 vars and read-only variables are referred to as vals. 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.