Variables are the names you give to computer memory locations which are used to store values in a computer program.
They provide a way to labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves as well.
It is helpful to think of a variable as a box that stores particular values. Their sole purpose is to label and store data in memory. So that data can be used easily throughout your program.
There are two types of variables in kotlin:
Mutable variables (declared using
Immutable variables (declared using
To declare a variable in kotlin, either
valkeyword is used.
There are only two possibilities in kotlin for variable declaration.
- Through Type Inference (where inline initialization is compulsory)
- Through explicit data type declaration (here you can initialize variable later)
Syntax for Declaration through type inference
var VariableName = value //Initializer is compulsory val VariableName = value //Initializer is compulsory
Syntax for explicit data type declaration
var VariableName : data type = value //Initializer is optional val VariableName : data type //Initializer is optional VariableName = value // initialize value at this point
val language = “French” var score = 40
Here, language is a variable of type String and the score is a variable of type Int.
You don’t have to specify the data type of variable in kotlin.
Compiler knows this by initializer expression like here, it knows that “French” is a string, and 40 is a integer value in the above program. This is called Type Inference in programming.
However, you can explicitly specify the data type if you want. For example.
var language: String = “French” val score: Int = 40
As you can notice, in kotlin we first write the variable name and then put a colon and then specify the data type of that variable.
We have initialized variable during declaration in above examples.
However, it is not necessary, you can declare the variable and specify its type in one statement and initialize the variable in another statement later in the program.
var language : String language = “Marathi” val score //Compile time Error Score = 60 //Compile time Error
- In the last statement, the type of language variable is not explicitly specified, nor the variable is initialized during declaration which can cause a compile-time error. You have to choose one of them either initialize variable during declaration or explicitly specify its data type.
So, guys, that’s it for variables in kotlin. This is pretty much in-depth detail about variables. That’s it for today guys. Please check every day for more articles.
Till then Keep Coding, Keep Loving.
Jai Hind, Vande Mataram 🇮🇳
Wanna get in touch with me? Here are links. I’ll love to become your friend. 😊