In the previous article, we restricted outer implicit receivers’ access to inner lambdas and we finished our DSL. In this article we will play around a little bit with our DSL and we will draw a few conclusions.

As I mentioned in the introduction of this series, an internal DSL is built on top of a GPL and exists along with it. This allows us to write code in that GPL combined with code in our DSL without generating errors. For example, we could create shapes of type Triangle inside a loop as follows:

The previous code outputs the following:

You could even add shapes to a list and merge them all with the intersection operation:

The previous code generates different outputs because of the random operations. One of those outputs is the following:

It seems to work flawlessly, however, I want you to try one last thing before we finish. Let’s create a ComposedShape from 3 shapes created directly inside its composed function lambda:

The previous code outputs the following:

As you can see, every shape created inside the lambda of the composed function is added to the Panel, although clearly that’s not our intention. This is a problem that can be solved easily by modifying its receiver. I suggest you to practice what you have learned throughout this series and solve this issue on your own until it outputs the following:

💬 You can find the solution under the branch dsl-enhanced in the project Shapes-DSL.

I’m sure that when you started this series and looked at the cover image, it seemed like any other code with no importance. But, as you progressed throughout this series, your perception changed so now you can’t look at the image without thinking about the code under the hood that allows us to express those instructions the way it does.

With all the knowledge you have acquired at this point, you can create a DSL either because you are creating a library, because you are working on a complicated module, or because you want to simplify code that you consider verbose or difficult to read.

Take advantage of the power of Kotlin and create elegant code that makes the reading, maintenance and scalability of a system easier and time-saving, every developer in your team and even yourself in the future will be grateful.

💬 If you enjoyed this article, you can show your appreciation by buying me a coffee at the link below. Thanks for reading and for your support.

--

--

Glenn Sandoval
Kotlin and Kotlin for Android

I’m a software developer who loves learning and making new things all the time. I especially like mobile technology.