Recent releases of Java have had some very noteworthy and developer-friendly features including a concept of record classes. From the Java docs of the Record class:

A record class is a shallowly immutable, transparent carrier for a fixed set of values, called the record components. The Java language provides concise syntax for declaring record classes, whereby the record components are declared in the record header. The list of record components declared in the record header form the record descriptor.

My first thought on seeing this class and as someone who has used Kotlin for some time now, I couldn’t help but wonder how similar this sounds to Kotlin’s data classes.

So I did some exploring and here is my first impression comparing Java’s records to Kotlin’s data classes. But before that, let us take a quick look at what these are and how we can create one:

Records

public record Sample (String key, String value) {}

A record is a data holder that extends from Java’s base Record class. A key feature of records classes are

  • All properties are final and private.
  • Declaring a class using the record key word generates the equals()hashcode() and toString() methods hence reducing boiler plate code.

Data class

data class Sample (val key, val value)

Data classes are Kotlin’s data holder classes and some of its key features are:

  • Properties can be final or not (declaring properties as a var makes them not final and hence they can be changed).
  • Similar to record classes, declaring a class as a data class automatically generates the equals()hashcode() and toString() methods.

#kotlin #coding #java #kotlin-vs-java

Java’s Records vs Kotlin’s Data Classes
2.35 GEEK