Hello friends, This is the “Ultimate Guide to Kotlin variables”. In this tutorial, we will learn about Var and Val. We will be discussing the difference between Var and Val variables and mostly where we should use Var and Where we should use Val in Kotlin. So let’s get started.
From the beginning of programming language development, variables are crucial in software development. As in beginner language, “Variables are used as data containers which store different data type values”.
Ultimate Guide to Kotlin Variables Var vs Val Explained:
1. Var(Mutable Variable):
A variable declared with var is mutable in Kotlin meaning its assigned value can be changed or reassigned multiple times throughout the program. It is very helpful for scenarios where data can be updated dynamically within the program. There are two different ways in Kotlin to declare a variable With Typecasting and Without Typecasting(also known as type interface).
Typecasting Var syntax:
1 |
var variableName: DataType = value |
Example:
1 2 3 4 5 |
var myAge: Int = 18 age = 28 age = 30 |
Without Typecasting interface:
1 2 3 4 5 |
var city = "New York" // Type inferred as String var myAge = 30 // Type inferred as Int var tempValue = true // Type inferred as Boolean |
2. Val(Immutable Variable):
A variable declared with val is immutable, which means its value cannot be changed after it’s assigned. val is the same as the final variable in Java.
Typecasting val syntax:
1 |
val variableName: DataType = value |
Example:
1 2 3 |
val name: String = "John" // name = "Doe" // Not allowed with val |
Without Typecasting val syntax:
1 2 |
val pi = 3.14 // Automatically set data type as Double. val name = "John" // Automatically set data type as String. |
Happy reading.