In this tutorial you will learn about Kotlin variables.
In programming world, variable is responsible for storing some value. The value is stored at some memory location. A memory location or address may look something like 0x7ff9c05f. It is not easier to remember or use it to access the value stored at the memory address.
Variables are just name given to these memory address. As variables are written in human readable language so it is easier to access memory address using them.
Kotlin Variables
In simple words we can say that, variables are the name given to memory locations which are used to store data or values.
How to Declare Variable in Kotlin?
In Kotlin variable can be declared using var and val keyword. Lets take one example to understand it.
var number1 = 10 val number2 = 15
Here I have not mentioned the data type of variable. Compiler takes the type depending upon initialized value. If we initialize variable at the time of declaration then mentioning data type is optional. In above case number1 and number2 are Int type.
var: Variable declared using var is mutable. It means we can modify its value anytime.
val: Variable declared using val are read only. It means we can’t modify its value once assigned.
Also Read: Kotlin var vs val – Difference between var and val
var number1 = 10 val number2 = 15 number1 = 20 //works fine number2 = 30 //will show error, can't modify the value later
You can also specify the data type.
var number1: Int = 10 val number2: Int = 15
Lets take few more examples.
var number1: Int //works fine number1 = 10 var number2 //will show error, we have to mention the data type because variable is initialized later number2 = 20
In Kotlin we can’t declare multiple variables in single line.
var number1 = 10, number2 = 20 //will show error
Declaration for each variable should be done in separate line.
This was all about Kotlin variables. Comment below if you have any queries regarding it.