4

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?

Viktor
  • 1,298
  • 15
  • 28
  • I don't know such solutions(like Lombok @toString), perhaps you can implement an abstract class and override toString once using reflection to make it general, but not looks like nice idea. or try to ask in Kotlin slack channel, there are lots of JB guys, they know it better – dzrkot Nov 23 '17 at 13:25
  • Possible duplicate of [Kotlin - generate toString() for a non-data class](https://stackoverflow.com/questions/40862207/kotlin-generate-tostring-for-a-non-data-class) – Salem Nov 23 '17 at 14:07
  • Is there a reason you do not want the additional methods, or is it just to reduce the amount of methods? – jrtapsell Nov 23 '17 at 15:27

1 Answers1

0

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.

Salem
  • 13,516
  • 4
  • 51
  • 70