What if you could stop accidental changes in your code before they even happen?
Why Properties with val and var in Kotlin? - Purpose & Use Cases
Imagine you have a notebook where you write down your daily tasks. Sometimes you want to keep a task as it is, and other times you want to be able to change it later. Without a clear way to mark which tasks can be changed and which cannot, you might accidentally erase or alter important notes.
Manually tracking which values should stay fixed and which can change is confusing and error-prone. You might overwrite important data by mistake or waste time checking if a value should be updated. This slows down your work and causes bugs.
Kotlin's val and var keywords let you clearly mark properties as read-only or mutable. This way, the compiler helps you avoid accidental changes and makes your code safer and easier to understand.
class Task { var description: String = "" fun updateDescription(newDesc: String) { description = newDesc } }
class Task(val id: Int, var description: String)This lets you write safer and clearer code by explicitly controlling which properties can change and which cannot.
Think of a bank account number that should never change once set (val), versus the account balance that updates with each transaction (var).
val creates read-only properties that cannot be changed after assignment.
var creates mutable properties that can be updated anytime.
Using them properly prevents bugs and makes your code easier to read.