Kotlin 101: val vs. var Behind The Scenes!
👋 Welcome!
Are you learning Kotlin and feel curious about val
and var
? In this article we will dive into their characteristics, differences and use cases!
val
and var
are keywords used to define if the value of a variable or property can be reassigned of if it should remain unchanged throughout your program. Sounds exciting, right? This can really help you prevent bugs, so let’s begin!
💻 To Follow Along:
If you would like to practice these examples as you read the article, you can use the Kotlin REPL on IntelliJ by clicking on:
Tools -> Kotlin -> Kotlin REPL
You should see the Kotlin REPL at the bottom:
💡 Note: To execute commands, click on Ctrl + Enter
.
🔎 Main Difference:
Now let’s dive into the main difference between val
and var
:
- Adding
val
before the variable declaration makes the variable read-only which means that once you define the variable and assign a value for the first time, you cannot change it. - On the other hand, adding
var
before the variable declaration makes the variable mutable, which means that you can change its value as many times as you need.
🔧 Now… Use Cases!
There are two main scenarios where you will need to use them:
- When you define variables.
- When you declare properties for your classes.
Let’s dive into each one of them in detail! 🎆
1️⃣ Define Variables
The general syntax to define variables in Kotlin is:
<val or var> <variableName> = <value>
The data type will be inferred automatically but you can optionally declare it explicitly by using this syntax:
<val or var> <variableName>: <dataType> = <value>
✅ The Power of Val
Let’s check out some examples of val
in action!
Let’s say we are developing an Android app that need to keep track of the user id. We define a variable to store this value:
val userId = 6
You’ve just defined your first variable in Kotlin! Congratulations! 🎉
Now let’s see what happens if we try to change the value assigned to userId
userId = 5
error: val cannot be reassigned // Error message!
You see an error message saying that this variable cannot be reassigned because we used val
to define it which makes it real-only, you cannot change its value.
💡 Note: This is very useful to create variables that should not be accidentally modified.
Alternative Syntax for val:
You can also declare a variable using val
by explicitly declaring the data type:
val userId: Int = 125663
💡 Note: You need to explicitly declare the data type if you define the variable without assigning a value for it immediately, for example:
val userId: Int // Define the variable and include the data type Int// CodeuserId = 5 // Assign value for the first time
⚠️ This syntax will throw an error in Kotlin REPL!
error: captured member values initialization is forbidden due to possible reassignment
To use it you will need to create a new Kotlin file (.kt
) on IntelliJ with a main function, for example:
fun main(args: Array<String>) {
val num1: Int // Define variable
for (i in 1..5) { // Code
println("Hi")
}
num1 = 5 // Assign value for the variable
}
⚠️ If you try to assign a new value after the first assignment, you will get an error as you can see below:
val userId: Int // Include the data type Int// CodeuserId = 5 // Assign value for the first time// CodeuserId = 3 // Throws the error "Val cannot be reassigned"
✅ The Power Of Var:
Now that you know more about val
, let’s check out an example of var
in action!
Let’s create a new variable to store the name of the user:
var userName = "Noris"
If you want to reassign this value, you can do so because we used var
when we defined the variable, making it mutable.
userName = "Nora"
and now the value of userName
is “Nora”
.
The data type is inferred if it’s not explicitly declared. In this case, the value is a String.
To learn more about defining variables in Kotlin:
2️⃣ Declare Properties of a Class
Now let’s dive into the use cases of var
and val
for Object Oriented Programming!
Let’s say we are creating an Android app for an NGO that monitors trees in Africa. We create a class to represent a Tree with two properties numberOfLeaves
and id
:
class Tree(var numberOfLeaves: Int, val id: Int) {}
⚠️ Note: Notice that we are using var
for numberOfLeaves
because this property will vary in time and we are using val
for id
since the id will remain unchanged.
Now let’s create a tree
instance with 50 leaves and id 2573:
var tree = Tree(50, 2573)
Since we make the number of leaves a mutable property, we can modify this value after we create the instance:
tree.numberOfLeaves = 55
and the value will be updated.
But…
If we try to assign a new id for the tree instance:
tree.id = 2402
We get this error:
Kotlin: Val cannot be reassigned
💡 Note: this is very helpful to avoid modifying properties that should remain unchanged.
To learn more about properties in Kotlin:
👍 Congrats!
Now that you know the difference between val
and var
you can start applying your knowledge to new projects. Awesome! 🎉 👏
If you liked this article, your claps 👏 are very much appreciated to help developers who are embarking on this journey find it as well. 😃 Thank you very much in advance!
Follow Techmacademy on Medium and Twitter to find interesting articles on the fundamentals of programming.
I would really love to read your comments and thoughts. 😃 👍