Kotlin DSL Basics in Android

Burak Demir
turkcell
2 min readJan 27, 2022

--

If you are a programmer who develop Android with the Kotlin language maybe you used DSL knowingly or unknowingly.

Basically DSL, computer languages ​​created for specific application domain.

Our purpose in using DSL is to make the code more readable and simple. I will sharing how i created a simple DSL in my project. It’s up to you to make it more useful with more complex examples. The sky is the limit.

I have a library and some parameters need to set from outside.

I have a model class as below.

How will it look with Kotlin DSL

First thing user that entry point of DSL. user Function takes a lambda as a parameter.

How looks like user function signature:

This function accepts a lambda expression that will be run within the context of the User class.

Simply thing done here create a User class then apply given lambda and return receiver of type.

For Log & Location class look like this:

And log and location functions

We have built our first Kotlin DSL. Finally we can create User class like this.

That’s all

Until next time, let’s write the code more readable.

Do you think is it a good way to use a lambda function to write Kotlin DSL is good way? If you used a different way to write more readable code, I would be glad to see it in the comment section.

--

--