Search code examples
inheritancekotlinpojodata-class

Inheritance of data class in Kotlin


I know that there are limitations in Kotlin to inherit from a data class. I learn't more while going through this discussion.

As data class in Kotlin are similar to POJO in Java. Should we not follow inheritance in Java POJO classes as well? To sum it up, is it because of the limitations in Kotlin that we are are not allowed to inherit from data classes or there is a flaw in design if you are doing so.

To break it down into a simpler question. Is it wrong to inherit from a POJO class in Java?


Solution

  • A data class is not the equivalent of a POJO, it does more than that, which is why its inheritance is restricted.

    Take a simple POJO:

    public class User {
    
        private String name;
        private int age;
    
        public String getName() { return name; }
        public int getAge() { return age; }
    
        public void setName(final String name) { this.name = name; }
        public void setAge(final int age) { this.age = age; }
    
        public User(final String name, final int age) {
            this.name = name;
            this.age = age;
        }
    
    }
    

    The equivalent of this in Kotlin is not a data class, but just a simple class like this:

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

    This will create two mutable properties (fields, plus getters and setters), and the constructor. This is already equivalent to the above POJO.

    What adding the data modifier does on top of this is generate equals, hashCode, toString methods. It also adds some Kotlin-specific methods: componentN methods for destructuring declarations, and the copy method.

    These generated methods, specifically the first three mentioned above get complicated to define if data classes inherit from each other. See this in detail in the KEEP about this topic. See also this and this discussion on the topic.