Java Records vs Kotlin Data Classes

Viewed 1992

Java 14 offers a new feature called Records, helping to create javabeans.

I've been using Kotlin for a couple of times, and of course, Java Records remind me Data Classes.

Are they completely similar? Or are there fundamental differences between them apart from the languages syntaxes?

1 Answers

This is a great article about all those differences.

In summary:

Similarities

  • generated methods: equals, hashCode, toString
  • generated constructor
  • generated getters (but Kotlin getter is called o.name, while Java uses o.name())
  • can modify the canonical constructor
  • can add additional methods

Differences

Kotlin's data classes support many other little things:

data class (Kotlin) record (Java)
copy method for easier object creation no copy method
variables can be var or val variables can only be final
can inherit from other non-data classes no inheritance
can define non-constructor mutable variables can define only static variables

Both are great for reducing the code bloat.

Related