more-readable-xml-generating-code

How to make XML-generating code more readable with Kotlin extensions and lambdas

XML-generating code in Kotlin may not be readable enough by default. Thankfully, using Kotlin extension functions and lambdas with receiver, we can improve it significantly.

Recently, during Kotlin 1.1 Launch Meetup, I gave a short speech about how we used Kotlin’s extension functions and lambda with receivers to make XML generating code more readable. I want to share with you a few ideas I’ve came up with, using Kotlin.

First of all, we want to create XML document from a very big collection of objects. Because of that we want use XML stream API instead of creating a document in memory. We will use javax.xml.XMLStreamWriter.

We want to serialize the following objects:

We will operate on the tiny data set for the tests:

By doing serialization, this should be your final result:

XMLStreamWriter API is rather verbose, as you can see below.

Thankfully, with a few extension functions accepting lambda with receivers, we can make the code much more readable:

Interestingly, the code above does the same as the first sample! It calls methods on the writer in the same order. But at the same time it is much easier to read and modify.

Time to see what kind of code let that magic happen!

If you need more details on how extension functions and lambda with receiver work, check out the Kotlin reference:

Want to play with the code for yourself? No problem, just click here to find in on my GitHub profile. It contains a few incremental steps leading to the final solution.

Subscribe to our newsletter
Menu