Kotlin Data class v/s open class?

B.shruti :

As I am converting my java project to kotlin project, I came to know about data classes in kotlin(replacement of Java model classes).

Now I have a requirement for my kotlin data class to support RealmObject but as per the link Kotlin data class of RealmObject, it says data classes are apparently not supported in Realm, so I need to make my data class as open class.

So basically, I want to know the difference between these two terms.

GhostCat salutes Monica C. :

Data classes are intended to hold values. In the Java Bean sense, their main purpose is to wrap around some set of values.

What makes Java beans really ugly is that many important methods, such as equals(), hashcode() or toString() that ideally should know about the fields of your class ... are inherited from java.lang.Object. And thus they do nothing useful.

When you declare a data class in Kotlin, the Kotlin compiler simply adds a reasonable implementation for all these methods. See kotlin-lang:

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • equals()/hashCode() pair;
  • toString() of the form "User(name=John, age=42)";

In other words: when that User class is a data class, and when you have two users objects declared with User(name=John, age=42), then those two objects will be equal, because the generated equals() method will compare the name and age within those data class objects.

An Open class on the other hand, is an ordinary class that is open for extension. Meaning: by default, when you write a class in Kotlin, it can not be extended. Yes, inheritance is prevented by default. By declaring a class to be open, you tell the compiler: "I intend to extend this class". In other words: if you want to have Child extends Base, then your Base class must be declared open in Kotlin.

In short: data classes are meant as containers for values, that can be used as that. Open is a different concept, it simply boils down to: can be inherited (respectively overridden when talking about methods) by some child class.

Long story short: in that question you are linking to, you are told:

  • you can't use Realm to process data classes
  • and the example given there simply assumes that maybe you want to extend that Person class, so it is declared `open``

I guess: unless you intend to create subclasses of your classes, you simply go without the open keyword! Write standard kotlin, and make them open if they are intended to be extended.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128331&siteId=1