Published on

Generating Builders for Kotlin classes in IntelliJ


Today was spent doing more code reviews. One of the classes I was looking at had a bean with a large unwieldy and unreadable constructor. I wanted to improve this to make the code easier to understand.

In these situations I normally generate a builder for these beans and use that to construct the bean in a more readable fashion. IntelliJ has an excellent builder plugin which makes creating builders for Java classes trivial - in any Java file you can push alt+insert and choose the builder option from the menu. The problem is that this does not currently work on Kotlin files. This option appears in the insert menu and creates a builder class but returns an error and leaves the generated class empty.

After trying a number of things I worked out that the easiest was to make an exact copy of the Kotlin class as a Java class then generate the builder and delete the Java class. As Kotlin and Java are interoperable this works as long as the Java version of the copied Kotlin class has the same constructor signature. Until I find a better way of doing this I will stick to this approach.

One thing worth noting is you can often get around using a builder if you are constructing a Kotlin class in Kotlin files by using named parameters which improves readability like builders and also enforces required fields (something builders cannot do easily without introducing a huge constructor again).