In Kotlin, we can use both variables as well as constants (read-only variables). Depending on the instructions provided to the Compiler, we can store static as well as dynamic values to the Variables. In case, our stored value is dynamic hence var keyword will be succeeded by variable name. On the other hand, val keyword in place of var if the value so stored is static. In this article, we would discuss different options available to declare variables in Kotlin.
Declare Variables in Kotlin
In Kotlin, we can initialize variables without even specifying its type. On the contrary, if we don’t initialize the variable then we have to mandatorily declare its variable type. For instance –
Kotlin compiler would take a variable of int type with value 6. In case we intend to initialize variable at a later stage then we can just declare its variable type –
val a: Int a=6 //initialize the variable later
If we choose to skip variable declaration and just initialize it. The compiler even then is capable to identify the variable type on its own. We call this mechanism type inference.
Furthermore, there are two references available to us for declaring variables. These are –
- Immutable References (val keyword) and,
- Mutable References (var keyword).
For Immutable references (val keyword), the value stored in the variable is considered as read-only. Thus, it is not possible to reference the variable to some other value. In other words, once variable declaration and initialization is done we are not allowed to make further modifications to it. For instance –
val x="Hello" val y: Int y=24 var x="World!" //This will throw an error y=48 //This will throw an error
For Mutable references (var keyword), the value stored in the variable can be reassigned. Therefore, to make desired modifications we prefix var keyword before the variable name. For instance –
var x: Int x=7 x=10 //It will reassign the value of x as 10
It is worth mentioning here that, we can’t change variable type through initialization once our variable is declared.
var x: Int //We have declared variable as Int x="Hello" //We are initializing a string to x
The above code will throw a type mismatch error and it won’t compile. Also, a variable prefixed with val keyword cannot be modified later so it needs to be initialized when created.
In conclusion, we discussed how to declare variables through val and var keywords.