Variables are the names given to the memory locations that are used for storing values. These values are retrieved and accessed via associated variables. Variables play a significant role in any program. Even though Kotlin is a statically typed programming language, pre-declaration of variable type is not necessarily required since Kotlin is capable enough to recognize the variable type through the assigned value. Variables are created using a var or val keyword. An equal to sign (=) is used for assigning the values to the variables.
Syntax:
Example:
fun main() {
var fname = "Elena"
var age = 10
println(fname)
println(age)
}
One way of retrieving the value of the variables has been shown in the above example. Another way of accessing the variable value is using a dollar ($) sign. Take a look at the following example.
fun main() {
var fname = "Alyna"
var age = 10
println("First Name is $fname")
println("Age is $age")
}
Now, there is also a third way of displaying the variable value. Here’s how you can do that:
fun main() {
var fname = "Alyna"
var age = 10
println("First Name is " +fname)
println("Age is " +age)
}
Mutable Variables: The variables whose values can be changed are known as mutable variables. For defining mutable variables in Kotlin, we use the keyword ‘var’. It indicates that the variable can be reassigned with a new value. These variables are defined when we need to keep changing their values depending upon different conditions in the program.
fun main() {
var fname = "Alyna" //mutable variable
var age = 10 //mutable variable
println("First Name is " +fname)
println("Age is " +age)
fname = "Suzi" //Reassigning mutable variable fname
age = 12 //Reassigning mutable variable age
println("First Name is " +fname)
println("Age is " +age)
}
Read-Only Variables: The immutable variables in Kotlin are called read-only variables since its value can only be retrieved and used but cannot be changed. For defining such variables in Kotlin, ‘val’ keyword is used. Once a value is assigned to a variable defined using the val keyword, it cannot be reallocated to a new value. We prefer defining read-only variables for constant values so that their value cannot be changed throughout the program. If we try to reassign a read-only variable, an error is raised as shown in the following example.
Example:
fun main() {
val fname = "Alyna" //read-only variable
val age = 10 //read-only variable
println("First Name is " +fname)
println("Age is " +age)
fname = "Suzi" //Trying to reassign a read-only variable
age = 12 //Trying to reassign a read-only variable
println("First Name is " +fname)
println("Age is " +age)
}