O'Reilly logo

Kotlin Programming: The Big Nerd Ranch Guide, First Edition by David Greenhalgh, Josh Skeen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required