Junior — Middle
Can you apply the inner modifier to a data class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the inner modifier is used for nested classes to give them access to members of the outer class. However, a data class cannot be declared with the inner modifier.
The reason is that data class automatically generates methods like equals(), hashCode(), toString(), based on constructor parameters. An inner class contains an implicit reference to the outer class, which complicates the semantics and can cause issues during method generation.
If you need a nested class with access to the outer class and also want it to be a data class, you should reconsider the architecture or use a regular class with the necessary methods.
Example that will not compile:
inner data class UserData(val name: String)
The compiler will give an error.