Variables in Kotlin

By | April 16, 2020

In this tutorial, we will learn about Variables in Kotlin. The main motive of variables is to store data in memory while execution of a Kotlin program. The value of variables can be changed throughout the execution of the program and we change reuse variable any number of times throughout the program.

In Kotlin we have two keywords to declare variables.

  • var(Mutable variable): We can change the value of the variable which declared using the var keyword.
  • val(Immutable variable): We cannot change the value of the variable which declared using val keyword.

Example of Variable using var keyword:

var lang = "Java"  
val age = 22  

Here is a really important thing to note about Kotlin variable we don’t need to explicitly define the type of variable. Kotlin compiler automatically takes data type according to the value of the variable. This is known as type inference in programming. We also have another option if a programmer wants to write datatype explicitly he/she can write. Check out the example.

var lang: String = "Java"  
val age: Int = 22  

Example of Variable using val keyword:

var lang = "Java"  
//We cannot change value of this variable
lang = "Python" //This line will show error