Sobes.tech
Junior — Middle

Mis vahe on väljade deklaratsioonil konstruktoris ja andmeklassi põhikehas?

sobes.tech AI

Vastus AI-lt

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

Example:

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

Here, name and age are properties of the class.

If, on the other hand, 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 in the primary constructor makes the field part of the class's "data", while declaring inside the body is just an additional property.