A variable is a named area in memory used to store and process data. A variable in Kotlin always has a name, a data type and a value. The name of the variable is a freely selectable identifier that can consist of alphanumeric characters or underscores and must begin with either a letter or an underscore. To define a variable in Kotlin you can use two keywords val or var should be used.
The syntax for defining a variable in Kotlin is as follows:
A variable is defined by first using the keyword val or var is used, followed by the variable name and a colon after which the variable type is specified.
In the example below, variable age with the type Int (for integer values without decimal places) declared:
The next step, a value is assigned to the variable age:
In the final statement, the assigned value is output using the function println ():
Immutable and mutable variables
There are two types of variables in Kotlin: immutable and mutable. Immutable variables are created using the keyword val declared and can only be initialized once with a value. Attempting to change the value of a val variable will produce a compilation error.
Mutable variables are declared with the keyword var and can be updated multiple times with different values during the runtime of the program.