ProgrammingBackend Developer

What is the difference between the keywords "val" and "var" in Kotlin? How to use them optimally in terms of code safety and performance?

Pass interviews with Hintsage AI assistant

Answer.

val and var are both used to declare variables, but they have fundamental differences:

  • val (value): declares an immutable, read-only reference. After initialization, the value cannot be reassigned, the reference remains permanently to one object:
val number = 42 // number = 10 // error!
  • var (variable): declares a mutable variable;
var counter = 0 counter++ // allowed

Safety and Performance:

  • It is preferable to use val everywhere the variable should not change — this protects against accidental changes and makes the code easier to understand.
  • Using val allows the compiler and IDE to catch errors at compile time and optimize the code.

Trick Question.

Can an object declared as val be 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.

Examples of real errors due to lack of knowledge of the subtleties of the topic.


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.