Pretty print data class

I have an object graph of collections of data classes deserialized from JSON. I want to print that out and eyeball it as a sanity check, but the standard generated toString format is a single long line that’s not very helpful.

Is there a utility to modify how the generated toString renders?

For quick purposes I can thrown in a result.toString().replace("), ", "),\n ") I guess. I don’t want to override the toString on all these classes; I just want a quick way to express their contents in a way I can read while I’m working. Or does kotlinx-serialization perhaps have a pretty print utililty somewhere?

Aside from a string replace, or maybe using the visiter pattern to walk your object tree, I’m not sure there’s a quick and easy option (unless someone else knows of a library that already implements something?).

Data classes are compiled with their componentN functions and as far as I know, there isn’t some compiler API to tweak how the toString generated for data classes.
You could use refection and get the componentN functions in order to customize printing at runtime for any given class. I suspect that isn’t as practical as changing the string afterward.

Personally, if I was wanting this and only needed it for quick sanity checks, I’d do what you suggested and wrap it in some function like fun Any.prettyPrint() { /* ... */ }. I might go as far as to count parentheses and add some indentation if I really needed it. Any more than that would require me to use it for more than a visual check.

You said that your data classes are deserialized from JSON. That means you have a serializer. You could just serialize it to json and add a indent :wink:. Pretty sure kotlinx.serialization has an option for that.


Well, the serialization layer is what I’m working on, so there’s some transformation and potential buggyness involved. And for any touch ups, I don’t want to have to throw in model annotations for an ad hoc, temporary use case. I think something like this probably suits my purpose, though at the expense of a one-off dependency.

1 Like