Allow customization of data class toString

When using data classes for toString you only have 2 choices: take its default generated toString or write it all yourself. In my case one of my data class properties is a lot of text that I really don’t need to see all of. It would be nice if there were a way to customize the generated toString behavior by annotations on the properties. Ideally there would be an annotation that says to exclude this property from toString and another one that says truncate and ellipsize the output for this property to a certain max number of characters.


Or perhaps simpler is just an annotation that lets you specify formatting of the property which could handle both cases.

At this time we have no plans to make this customizable. There are so many different requests for customization of generated methods that we’d probably need to support fifteen different annotations with many different parameters to cover all possible use cases, and the end result would be much less maintainable than simply hand-written implementations.

The IDE has support for generating toString() for you - you can use that and then make any necessary customizations by editing the generated code.

Which is fine if there are never any changes to the data classes. Explicitly coding it means it also has to be maintained when the data class changes.

1 Like

You can fix it by reflections, or use some kind of annotation processor to auto-generate what you need.

I use the following library for data classes. It does toString() and hashCode() for you.

How about Lombok? Does exactly what you want!

I think the defaults for data classes are pretty sane, and there is room for improvement.

If the minimum"contract" of a data class is that all constructor parameters are also available in copy() and as componentN functions, then a single annotation @Generate(toString=false, equalsHashCode=false) would help prevent most ‘other’ problems.

  • @Generate(toString = false) would exclude it from being added to toString
  • @Generate(equalsHashCode = false) would exclude it from being added to equals and hashCode


  • Circular references in fields
  • JPA @OneToMany and @ManyToOne duality
  • ‘Business Key’ equality

One could even imagine to use such an annotation in the future to auto-generate toString and equals/hashCode for all other classes as well. With the difference being, that the default are

  • for data class properties @Generate(toString=true, equalsHashCode=true)
  • for all other class properties @Generate(toString=false, equalsHashCode=false) with no auto-generation happening if no @Generate annotation is present.

Would seem 2 separate annotations would make more sense than 1 annotation with 2 Boolean parameters. I would also like to see a way to annotate the formatting as well but not sure that can be done easily in an annotation.