Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Records vs Kotlin Data Classes

Tags:

java

kotlin

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?

like image 583
Bertrand Nau Avatar asked Oct 21 '20 16:10

Bertrand Nau


People also ask

When should I use Kotlin data class?

Answer: Kotlin provides a special type of class called data class, which is usually used for objects that act as a store for data properties and has no business logic or member functions. It provides a lot of advantages with reduced boilerplate code.

Can I use Kotlin data class in Java?

As a quick refresher, Kotlin is a modern, statically typed language that compiles down for use on the JVM. It's often used wherever you'd reach for Java, including Android apps and backend servers (using Java Spring or Kotlin's own Ktor).

What is the difference between Kotlin data class and normal class?

A data class is a class that only contains state and does not perform any operation. The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.

What is difference between record and class in Java?

Like enum , record is also a special class type in Java. It is intended to be used in places where a class is created only to act as plain data carrier. The important difference between class and record is that a record aims to eliminate all the boilerplate code needed to set and get the data from instance.


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.

like image 140
mrek Avatar answered Oct 18 '22 20:10

mrek