Kotlin – Variable

Kotlin Variable: Variable refers to a memory location. It is used to store data. The data of variable can be changed and reused depending on condition or on information passed to the program.Variable DeclarationKotlin variable is declared using keyword var and val.

var name ="apkzube"
val payment = 25

The difference between var and val is specified later on this page.
Here, variable name is String type and variable payment is Int type. We don’t require specifying the type of variable explicitly. Kotlin complier knows this by initilizer expression (“apkzube” is a String and 25 is an Int value). This is called type inference in programming.We can also explicitly specify the type of variable while declaring it.

var name: String ="apkzube"
val payment: Int = 25 

It is not necessary to initialize variable at the time of its declaration. Variable can be initialized later on when the program is executed.

var name: String
... ... ...
name = "Java"
val payment: Int
... ... ...
payment = 25
  • Here are few examples that results into error.
var name // Error
name = "apkzube"

Here, the type of name variable is not explicitly specified, nor the variable is initialized during declaration.

var payment: String
payment = 14 // Error

KotlinCopyHere, we are trying to assign 14 (integer value) to variable of different type (String).

Difference Between var and val

  • val (Immutable reference) – The variable declared using val keyword cannot be changed once the value is assigned. It is similar to final variable in Java.
  • var (Mutable reference) – The variable declared using var keyword can be changed later in the program. It corresponds to regular Java variable.

Here are few examples:

var language = "Nepal"
language = "USA"     

Here, language variable is reassigned to USA. Since, the variable is declared using var, this code work perfectly.

val language = "Nepal"
language = "USA"      // Error

You cannot reassign language variable to German in the above example because the variable is declared using val.

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.