Declaring Read-Only Variables

A closely-related keyword to var is val. It too can declare a variable… except that val variables are read-only. After you initialize them, they cannot be changed.

So, this works:

  val count = 5

  println(count::class)
  println(count)

This prints the type and the value, such as this Klassbook output:

class Int
5

You can modify a var value:

  var count = 5

  println(count)

  count = 7

  println(count)

This gives us:

5
7

However, this does not:

  var count = 5

  println(count)

  count = 7

  println(count)

  val readOnly = 5

  println(readOnly)

  readOnly = 7

  println(readOnly)

If you try running it, you will get a compile error:

e: klassbook.kt: (14, 3): Val cannot be reassigned

While we can fill a value into a var whenever we want, we can only fill a value into a val once, usually where we declare it.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.