Shorthand syntax for generating toString() method in Kotlin (for non-data classes)

Viewed 852

In Kotlin, it's possible to generate toString() method for data classes:

data class Foo(...)

But there are some limitations on using data classes, plus Kotlin compiler generates additional methods, which I don't want to have in my code.

In Java, you can generate toString() method with Lombok just by adding one line of code with @ToString annotation:

@ToString
public class Foo {
    ...
}

Unfortunately, Lombok doesn't work with Kotlin, so I have to implement toString() method manually each time:

class Foo {
    ...
    override fun toString(): String {
        // bunch of code here
    }
}

Is there any shorthand syntax for this in Kotlin or maybe some third-party solution?

1 Answers

If you allow Apache Commons Lang, you can use the ToStringBuilder which allows this:

override fun toString() = ToStringBuilder(this)
    .append("field1", field1)
    .append("field2", field2)
    .toString()

or, at the cost of some speed, a shorter reflective solution:

override fun toString() = ToStringBuilder.reflectionToString(this)

The format can be changed by passing a different ToStringStyle to the builder.

I don't believe Kotlin itself has any support for this.

Related