Why data classes in Kotlin cannot be marked with inner modifier?

Viewed 309

I have a simple class let's say User. Now I want to create an inner data class let's say UserProperty inside User class, but as soon as I add inner modifier to data class UserProperty the IDE complains about Modifier inner is incompatible with data. What am I missing?

2 Answers

On the one hand, inner classes use the outer instance as a hidden first constructor parameter (which is effectively private val). On the other, data class behavior exposes all constructor parameters, including their names (in toString()), so they "should be" visible. Plus, in this case

If a supertype has the componentN() functions that are open and return compatible types, the corresponding functions are generated for the data class and override those of the supertype. If the functions of the supertype cannot be overridden due to incompatible signatures or being final, an error is reported;

should component1() be the outer instance or the first parameter you actually wrote?

The designers likely decided any behavior would be surprising to enough users that it's better to disallow this at all. And if you want your UserProperty to be like an inner class, just add a User constructor parameter yourself.

An inner class instance is dependent on the existence of an outer class instance i.e You cannot have an instance of the inner class without the outer one. Now, if you try to store this object in the DB, the 'data' modifier declares the inner object as an own instance to be stored, with violates the constraints of an inner class.

If that would be possible, you could extract the information of the inner class without having the outer one on your stack, which is by definition invalid.

Therefore, you can only apply the 'data' modifier on the outer class.. it should store the inner class as well (have to check this). if you need the inner class independent in your DB, it should be an own class in the first place.

Related