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

0 Interaction
1.8K Views
Views
49 Likes

You need to be logged in to participate in this discussion.

ร—
×
×
๐Ÿช CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home