Kotlin DSL - let's express code in "mini-language" - Part 1 of 5

Kotlin DSL - let's express code in "mini-language"  - Part 1 of 5

In this series , we will take a look at what DSLs are and how to build our custom Kotlin DSLs and apply them to multiple use cases for Android.

What is DSL

The concept of DSL or domain-specific language is pretty simple.

A domain specific language is a construct that allows you to create things and set them up in a way that feels more natural and usually comes closer to proper language usage than normal code.

As the name implies, DSLs are only useful in a constrained context - the domain at hand. In contrast to general purpose languages (of which Kotlin is one), DSLs apply to a limited set of use cases only.

Why use DSL you ask?!

The main benefit of using a DSL over normal constructs?  Domain specific languages provide a more concise and at the same time much better readable API for a specific purpose, compared to the normal general purpose way to achieve the same.

There are broadly classified as External DSLs vs Internal DSLs.

DSL is important in any language - the more powerful abstractions a language offers, better the support for modeling DSLs.

External DSLs

Most DSLs are language independent. An external DSL is a language that's parsed independently of the host general purpose language, such as regular expressions, SQL, HTML, Gherkin,YAML.

Internal DSLs

Internal DSLs are a particular form of API in a host general purpose language, often referred to as a fluent interface or as i like to call it a mini language.

We all know that Kotlin is a flexible language - it’s part of the appeal! It’s actually so adaptable it gives us powerful tools to create a mini-language on top of it, that is better suited for a specific task at hand. Think about Anko, or Kotlinx.html or  custom DSLs.

The fundamental building blocks we have in Kotlin for building DSLs are Function Literals with Receiver,  the invoke convention , infix notation and extension functions.

In Part 2 of this series , we will take a look at the building blocks.