Java Records vs Kotlin Data Classes

5.6k views Asked by At

Java 14 offers a new feature called records, helping to create JavaBeans. What is the difference between Kotlin's data classes and Java records?

1

There are 1 answers

0
mrek On BEST ANSWER

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.