Variables – Getting to know more about them

In Kotlin we can have two types of variables:

  1. Mutable i.e. changeable meaning its value can be changed after it is declared for the first time.
  2. Immutable i.e. unchangeable meaning its value cannot be changed after it is declared for the first time. However we can still modify its value manually at the definition or declaration line.

Technically speaking, variables to which new values can be assigned are mutable variables. I will discuss with an example later.

Declaration

By declaration we mean defining the variables so that they can be used in code by their names. Naming a text string, number, piece of code or just anything valid is declaring variable.

This ability to name things help us greatly as we can insert, call, process the whole code by simply mentioning its name instead of copying and pasting all of it again and again. This gives us amazing flexibility while writing, reading, modifying and maintaining code.

  1. Mutable variables are declared using keyword var 
  2. Immutable variables are declared using keyword val

Syntax for both is same for declaration. Here is one example where two variables of two different types are declared:

And we can now print these two sentences by simply mentioning their names:

Changeable and Unchangeable

Now lets understand what I meant by “changeable” and “unchangeable” variable.

As I mentioned earlier, I can easily give any new value to var type variable. And the process of assigning new value is really easy. Simply mention the name and equate it to new value.

Say we want to change “Second” variables value to “Yes! I changed its value”:

This can be done by adding the following line of code before println() line. And if you run the program again, then it will output the new value assigned to variable Second:

However, if I try to do the same for variable First which is declared using val keyword, IDE will warn me with a red line under its name:

And if I insist on running the program, IDE will simply end up with an error that Val cannot be reassigned:

However, as I mentioned earlier, I can still change the value of First variable at the declaration line manually:

Leave a Reply

avatar
  Subscribe  
Notify of