Junior — Middle
Kas on lubatud kasutada muutujaid (var) data class konstruktoris Kotlinis?
sobes.tech AI
Vastus AI-lt
In Kotlin, in the constructor parameters of a data class, the modifier var cannot be used. The constructor parameters of a data class are by default val (immutable) or var (mutable), but when declaring constructor parameters, you must 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 var or val is not specified, the parameters will be just constructor parameters, but not properties of the class, and the data class will not be able to generate the necessary methods (equals, hashCode, toString) for them.
Therefore, it is not allowed to simply use var without val or var in the constructor parameters of a data class — you must explicitly specify var or val.