Understanding Variables in Kotlin
Think of variables as labeled boxes that store information. In Kotlin, we have two types of boxes: val (like a locked box) and var (like a box you can change). Let's learn which one to use and when!
๐ฆ What Are Variables?
Variables are like containers that hold your data. Just like you put toys in a toy box or food in the refrigerator, variables store information your program needs to remember.
Real-Life Example:
Imagine you have:
- โ
Your birth date - this never changes (use
val) - โ
Your age - this changes every year (use
var) - โ
Your current mood - this can change throughout the day (use
var)
๐ val - The Locked Box
Use val when you have information that won't change after you set it. Once you put something in a val box, it stays there forever!
Examples of val (things that don't change):
val myName = "Sarah" // Your name doesn't change
val birthYear = 1990 // Your birth year is fixed
val pi = 3.14159 // Mathematical constants
val favoriteColor = "Blue" // Your favorite color (usually stable)
โ ๏ธ Remember: If you try to change a val, Kotlin will give you an error!
val language = "Kotlin"
language = "Java" // โ ERROR! Can't change a val
๐ var - The Changeable Box
Use var when you have information that might change later in your program. You can take things out and put new things in!
Examples of var (things that can change):
var age = 25 // Your age changes every year
var temperature = 72.5 // Temperature can go up or down
var bankBalance = 1000.00 // Money comes and goes
var currentSong = "Song A" // You can change the music
โ This works perfectly:
var score = 0 // Start with score 0
score = 10 // Now score is 10
score = 25 // Now score is 25 - no problem!
๐ฏ Quick Guide: When to Use Which?
Use val for:
- Your name
- Your birthday
- Your ID number
- App version number
- Company name
- Mathematical constants
Use var for:
- Your age
- Your location
- Game score
- Shopping cart total
- Current time
- Battery level
๐งช Let's Practice Together!
For each situation, decide if you should use val or var:
1. Storing your email address:
val email = "[email protected]" // Email usually doesn't change
2. Tracking how many steps you've walked today:
var steps = 0 // Steps increase throughout the day
3. Storing the number of days in a week:
val daysInWeek = 7 // This never changes!
๐ Simple Rules to Remember
val = Value
Use when the value doesn't change
Like your birthday or your name
var = Variable
Use when the value can change
Like your age or your score in a game
Good Practice
Start with val whenever possible
Only use var when you really need to change the value
You need to be logged in to participate in this discussion.