Kotlin Variables are containers for storing data values. The data of variables can be changed and reused depending on conditions.
To create a variable we can use var or val, and assign a value to it with an equal sign (=)
Variable Declarations
Kotlin uses two keywords to declare variables val and var.
Example :
Var subject = “kotlin” Val salary = 21500
Here the variable subject is a string type and the variable salary is an int type. so we don’t need to specify the type of variable explicitly. Kotlin compilers know this by initializer Expression.
We can also explicitly specify the type of variable
Example :
Var subject: String = “Kotlin” Val salary: Int = 21500
You can also declare a variable without assigning the value, and give the value later. and this is only possible when you specify the type.
Example :
var subject: String subject = “Kotlin” println(subject)
Difference Between val and var
val (Immutable variable):- We can not change the value of variables declared using val keyword.
Example :
val subject =”kotlin” subject “java” error
var (mutable variables):- we can change the value of variables declared using the var keyword.
Example :
var salary = 21500 salary = 31500 execute