2

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?

Dinesh Singh
  • 727
  • 1
  • 10
  • 22

2 Answers2

11

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • What if we don't want the Kotlin compiler to generate getter / setter methods (like a Pojo with public fields for example) ? – Wolf359 Apr 11 '18 at 20:22
  • 1
    You can annotate each property with the [`@JvmField`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-field/index.html) annotation to do this. Doesn't change the syntax to access the properties in Kotlin, but you get direct field access instead of getters/setters in Java. – zsmb13 Apr 12 '18 at 04:05
5

In Kotlin, you can't inherit from a data class because there is no sensible way for the compiler to generate all the methods that are automatically provided for data classes.

In Java, there are no compiler-generated implementations of methods such as equals, hashCode and toString, and you're free to implement them in a way which would be the most sensible in your situation. Therefore, there's no reason why it would be wrong to inherit from a POJO.

yole
  • 92,896
  • 20
  • 260
  • 197