In this blog, we will look at how to write a DSL in Kotlin.

Some basic familarity with Kotlin or some understanding of how to write functions and classes in Kotlin will be required.

Table of Contents

1.0 What is DSL

This is what Wikipedia says about DSL:

domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains.

A domain-specific language is created specifically to solve problems in a particular domain and is not intended to be able to solve problems outside it (although that may be technically possible).

In contrast, general-purpose languages are created to solve problems in many domains.

Kotlin has many features that allow us to easily write type-safe DSL logic. e.g

  • Use of lambdas outside of method parentheses
  • Lambdas with receivers
  • Extension functions

We will look into them in detail later. Let’s look first at few well know examples of DSL.

 

2.0 Some common examples of DSL

2.1 SQL Queries

The SQL query language is the best example of a DSL. It is used to perform specific actions (insert/update/delete/query), on the given database only.

e.g.
select first_name, last_name from employee where age > 55;

2.2 HTML

e.g.

<html> 
  <body>
    <h1>DSL in Kotlin</h1>
    <p>This is a brief introduction to writing DSL in Kotlin</p>
 </body> 
</html>

 

2.3 CSS

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

.light-red {
  background-color: rgb(208, 243, 224);
}

2.4 Gradle Build Script

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    compile     "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.1"
    compile group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '0.23.3'
    compile 'khttp:khttp:0.1.0'
    testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0"
}