Sharing our technical trials in terms of Ubuntu software installs, Blogger hacks, Android and Kotlin learning.
Variables in Kotlin – Tutorials for beginners
Variables in Kotlin – Tutorials for beginners

Variables in Kotlin – Tutorials for beginners

Variables in Kotlin or any other programming language are used for holding values, a name is given to it so that it can be referenced by that name while using it later in the code.

The post is about variables in Kotlin, we will see how to declare a variable, how to define the type, if the value can be changed or not, examples and see what goes behind the scene when a variable is declared.

I. Syntax

  1. var x = 10
  • var is used when the value can change later in the code
variable declared using var

2. val y = 20

  • val is used when you want the value to remain same
variable declared using val

Looking at the syntax you can observe that when you declare a variable in Kotlin, you would be telling the compiler on

1. what is the name of the variable ?

  • so that it can be referenced using that name when you want to use it later

2. what is the type of the variable ?

  • If it is of the type int, string or boolean, based on the value it takes

3. Can the value assigned be changed later ?

  • To know whether or not you can change the value later on in the code

Example

  • var x = 10
  • name of the variable is “x”
  • type of the variable is int, based on the value 10
  • declared using var, value assigned can change

Behind the Scene

What happens when you declare a variable using one of the syntax var x = 10 or val y = 20 ?

An object is created, type of the object depends on the type of value assigned, since integer value is assigned in our example, the compiler creates an object of type Int and stores it in a memory location, and the variable holds reference to this object.

Tryout’s

Try out the following code:

1.

 fun main (args:Array<String>)
{

      var x = 10
      x= x+1
      println("Value of x now is "+x)
}

2.

 fun main (args:Array<String>)
{

      val x = 10
      x= x+1
      println("Value of x now is "+x)
}

Peek into the answer

  1. The first one complies fine and prints the result onto the console, as the value assigned to var can change

Output : “Value of x now is 11”

2. Second one gives compilation error, as the value assigned to val cannot change

Output: “Kotlin: Val cannot be reassigned”

Now that we have seen what variables are and how they are declared, in our post Types of variables we’ll explore more on types of values variable’s can take.