Variables

Variables are what we use to store values inside of computer programs, after that, we can use this stored information to do some process that uses this value.

In Kotlin we have two different ways to define variables, using the ‘val’ or ‘var‘ keywords.

Variable definition

In Kotlin, we start a variable definition with one of the available keywords,
‘val’ or ‘var’, followed by a name, then we use the equal sign, =, and finally, we assign a value to the variable. In the example below, the first variable’s name is age, and its value is 35, and for the second variable, the variable’s name is name, and its value is Alessandro.

var age = 35

val name = “Alessandro”

Var keyword

Variables defined with the var keyword are mutable variables, which means we can reassign a new value to these variables without the necessity of change their previous value. For example, we could reassign the number 60 to the variable age, after that, the variable age it’ll have a value of 60 and not 35 as assigned before. To change the value of this type of variable, we need to write the variable’s name, and then reassign a new value. We can do this change of value how many times we need. For example:

age = 60 // Now, the same variable age has a value of 60.

age = 15 // Now, the same variable age has a value of 15.

Val keyword

When we use the ‘val’ keyword in a variable definition, we are declaring a read-only variable, which means we can’t change its value later without changing its original value. We can’t do the same we did with the variable age to the variable name. For example, we can’t do what is shown below

name = “Sofia”

// This is not allowed in Kotlin for variables defined with a ‘val’ keyword.

When we defined the variable name, we used the ‘val’ keyword, so, we can’t call the variable later in a computer program and change its value.

I hope, I helped you to learn something!

See you next time!

You can see the code here: https://github.com/Aleangelozi/Kotlin/blob/master/src/0_variables.kt