8

Records are a new language feature since Java 14 (first preview) and Java 15 (second preview). As per my understanding they will be used to reduce boilerplate code in immutable data objects.

So this sigle line:

public record Person (String firstName, String lastName) {}

Is equivalent to declaring a class with private final fields, getter for each field, a public constructor and equals, hashCode and toString methods.

However this is pretty much the same as using lombok @Value annotation:

@Value
public class Person {
    
    String firstName;
    String lastName;
}

Other than you obviously doesn't need to deal with the lombok dependency, is there any advantange of using records?

pepevalbe
  • 1,340
  • 6
  • 18
  • If backwards compatibility matters use Lombok. If not use records. I think that's what it comes down to. – magicmn Feb 16 '21 at 09:15
  • 1
    They use using several annotations which is more verbose and don't produce final fields. I'm asking for @Value annotation which is almost the same to what a record is. – pepevalbe Feb 16 '21 at 11:34

2 Answers2

5

In addition to what Axel already suggested:

  • @Value generates immutable java beans while record is not a java bean.

  • Record is a built-in feature and it doesn't need any plugin or installation.

  • Lombok allows inheriting from a class while the record inherits j.l.Record. Extending a class generates a warning which is self-explanatory:

Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '(callSuper=false)' to your type.

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
4

IMHO the big advantage is that it's standard. Nearly everything we have in the standard library has been available in some variant prior to being standardized. But I much prefer to have everything working and being compatible than to have to deal with dependencies pulling in different versions of jodatime, lombok, etc.

But it will take some time before we will see JDK 16+ being widely adopted. So if you create an application and are free to choose the minimum supported JDK version, use records. If you create a library, you probably will aim for JDK 11 (because it's LTS) compatibility, and you have to use lombok.

Axel
  • 13,939
  • 5
  • 50
  • 79