Kotlin’s Builder DSL will change the way you code

Nishant Aanjaney Jalan
CodeX
Published in
3 min readMay 17, 2022
Source

If you haven’t read about Kotlin’s most powerful tool, you can check that out right here:

The first car was invented by Carl Benz in 1886. Since then, there have been so many developments and integration of new technologies. In 2022, cars are such complex machines that it requires a lot of manpower to build one.

We also are building cars, but with our brainpower…on a computer…in your room…isolated from the world…wait, there was a pandemic? OKAY — I am digressing 😜

Yay, we are making our complex car but wait, there are problems with this.

1. I need to make sure that I have all the required fields at the time of object construction. Hmmm.

2. My constructor parameters could change or increase which will clog the parameter list. Hmmm.

So what do we do it make this a little bit better?

Creating a Builder Class

Let’s have a look:

Hurray, we have made our complex object constructor a lot simpler. I do not need to have all properties at the same time, and the parameter list will no longer clog anymore.

Halt! Although this would be a better approach to constructing a complex class, there are still quite a few problems with this.

1. The parameter list is not clogging but the overall code is bulky. Hmmm.

2. Adding a lot of boilerplate code. Hmmm.

3. Not flexible in the code style. Hmmm.

So what do we do it make this a little bit better?

Kotlin DSL

Kotlin’s most powerful tool are the higher-order functions and a consequence is the ability to write type-safe DSL code.

Firstly, we can scrape off all the functions in the Builder class, and add this function to the top-level:

The buildCar function, in particular, is where all the magic happens. This function has a higher-order function with the Car.Builder being the lambda receiver class. When you write this lambda function, the implicit this will be of the Car.Builder class.

Wow, we have finally reached a stage where most of our problems have been resolved.

1. Code is very readable and clean.

2. We can add any logic inside the lambda parameter such as ifs or fors.

3. Flexible to even launch a coroutine if we are fetching data from APIs.

Conclusion

Kotlin’s Builder Interface along with DSL can boost your code’s readability and increase productivity within your team. With a small extra effort, this pattern can save time while refactoring and debugging code.

--

--

Nishant Aanjaney Jalan
CodeX
Editor for

Undergraduate Student | CS and Math Teacher | Android & Full-Stack Developer | Oracle Certified Java Programmer | https://cybercoder-naj.github.io