val and var are both used to declare variables, but they have fundamental differences:
val number = 42 // number = 10 // error!
var counter = 0 counter++ // allowed
Safety and Performance:
val everywhere the variable should not change — this protects against accidental changes and makes the code easier to understand.val allows the compiler and IDE to catch errors at compile time and optimize the code.Can an object declared as
valbe changed?
Answer: The value of the variable (the reference) cannot be reassigned, but if it is an object (like a list), its internal state can be changed.
val list = mutableListOf(1,2) list.add(3) // Allowed! However, list = anotherList will be an error.
Story
In the online store project, a developer defined the product list as
val items = mutableListOf<Product>(), thinking that this would make the list completely immutable. In fact, the list was changed in another part (a new item was added), which unexpectedly affected the display of the cart.
Story
In a parser for large text files, the array buffer was declared as
var buffer, even though it did not need to be replaced during parsing. An accidental reassignment to a new array occurred, leading to memory leak and incorrect data processing.
Story
In the code of one microservice, most variables were declared as
var"just in case", resulting in the object's state sometimes changing in different threads in large expressions, leading to elusive bugs due to race condition.