1 of 35

Kotlin DSL: The Charming Parts

Freddie Wang & Shengyou Fan

2 of 35

Who am I

  • Freddie Wang
  • Android engineer in SmartNews
  • ❤️ Kotlin ❤️

3 of 35

Who am I

  • 范聖佑 (Shengyou Fan)
  • Developer Advocate in JetBrains
  • 用力推廣 Kotlin 中 ❤️

4 of 35

Agenda

  • DSL at a glance
  • Kotlin syntax
  • Real world cases
  • Design your DSL
  • Q&A

5 of 35

What’s DSL

Designed for a particular application domain, not for general-purpose

  • SQL
  • Regular Expression
  • Gradle

6 of 35

External and Internal DSL

  • External: Independent syntax, need a parser to interpret the language
  • Internal: Written inside an existing host language.

7 of 35

Why Kotlin DSL

  • Top level functions, Extension function, Lambda with receiver make writing DSL very easily
  • Built-in type-safe support
  • Syntax sugar Lambda outside of parenthesis and Infix notation makes Kotlin DSL structured and good readability.

8 of 35

Kotlin Syntax

9 of 35

Top level function

10 of 35

Extension functions

11 of 35

Lambda with receiver

12 of 35

Infix notation

13 of 35

Real world DSLs

14 of 35

Real world cases

15 of 35

Gradle Kotlin DSL

16 of 35

Gradle syntax

17 of 35

Kotlin Gradle DSL

18 of 35

Kotlin DSL for HTML

19 of 35

HTML DOM

20 of 35

kotlinx.html

21 of 35

Exposed SQL Framework

22 of 35

Exposed SQL DSL

23 of 35

Generated SQL

24 of 35

Ktor Web Framework

25 of 35

Ktor Routing DSL

26 of 35

Write your own DSL

27 of 35

Design a mini app

28 of 35

Define the SimpleApp

29 of 35

Design the syntax (1/3)

30 of 35

Design the syntax (2/3)

31 of 35

Design the syntax (3/3)

32 of 35

Run the DSL

  1. Be part of the project
  2. Run it from external file
    • org.jetbrains.kotlin:kotlin-compiler-embeddable
    • ScriptEngine

33 of 35

Live Demo - Using ScriptEngine

34 of 35

Q&A

35 of 35

More cases