Sobes.tech
Junior — Middle

How justified is the use of the var keyword in defining a data class?

sobes.tech AI

Answer from AI

In Kotlin, when defining a data class, using the keyword var or val before properties determines whether they are mutable or not.

  • var — a mutable property, its value can be changed after the object is created.
  • val — an immutable property, its value is set once during creation and does not change.

Using var is justified if you really plan to change the property value after creating an instance of the class. If the object should be immutable, it is better to use val to enhance safety and predictability of the code.

Example:

data class User(var name: String, val id: Int)

val user = User("Alice", 1)
user.name = "Bob"  // allowed
// user.id = 2  // compilation error

Thus, the choice between var or val depends on the requirements for data mutability in your class.

How justified is the use of the var keyword in… - sobes.tech