Sobes.tech
Junior — Middle

Is it allowed to use variables (var) in the constructor parameters of a data class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, you cannot use the var modifier in the constructor parameters of a data class. The constructor parameters of a data class are by default val (immutable) or var (mutable), but when declaring constructor parameters, you need to explicitly specify var or val.

For example, a correct declaration of a data class with var:

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

If you do not specify var or val, the parameters will just be constructor parameters, not class properties, and the data class will not be able to generate the necessary methods (equals, hashCode, toString) for them.

Therefore, you cannot just use var without val or var in the constructor parameters of a data class — you must explicitly specify var or val.