What if your program could protect important values from accidental changes all by itself?
Why Val for immutable references in Kotlin? - Purpose & Use Cases
Imagine you are writing a program where you need to store a value that should never change once set, like a person's birth year or a fixed configuration setting.
If you use a regular variable that can be changed by mistake, you might accidentally overwrite this important data.
Using regular variables means you have to constantly remember not to change values that should stay the same.
This can lead to bugs that are hard to find because the program's state changes unexpectedly.
It's like writing important notes on a whiteboard that anyone can erase or change at any time.
Using val in Kotlin means you create an immutable reference -- once you assign a value, it cannot be changed.
This protects your data from accidental changes and makes your code safer and easier to understand.
var birthYear = 1990 birthYear = 1995 // Oops, changed by mistake!
val birthYear = 1990 // birthYear = 1995 // Error: Val cannot be reassigned
It enables you to write clear, reliable code where important values stay constant, reducing bugs and confusion.
Think of a recipe app where the number of ingredients in a recipe should never change once set; using val ensures the ingredient count stays correct throughout the app.
Val creates a fixed reference that cannot be changed after assignment.
This prevents accidental data changes and bugs.
It makes your code safer and easier to read.