Sobes.tech
Junior — Middle

What is the difference between declaring fields inside a constructor and in the main body of a data class?

sobes.tech AI

Answer from AI

In Kotlin, fields declared in the primary constructor (in parentheses after the class name) automatically become class properties with corresponding equals(), hashCode(), toString() methods, and are also involved in destructuring.

Example:

data class User(val name: String, val age: Int)

Here, name and age are class properties.

If a field is declared inside the class body (for example, inside the constructor or as a regular property), it will not participate in the automatically generated data class methods and will not be part of destructuring:

data class User(val name: String) {
    var age: Int = 0
}

Here, age is a regular property, not considered in equals and other methods.

Thus, declaring a field in the primary constructor makes it part of the class's "data," while declaring inside the body is just an additional property.

What is the difference between declaring fields… - sobes.tech