Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Type-Safe Builders: create a DS...

Rygel Louv
October 27, 2018

Introduction to Type-Safe Builders: create a DSL in Kotlin

In this talk we discover what DSLs are and how we can manage to build them in Kotlin. Building a DSL in Kotlin is just about manipulating known Kotlin features such as lambdas, extension functions, infix functions ect.

Rygel Louv

October 27, 2018
Tweet

More Decks by Rygel Louv

Other Decks in Programming

Transcript

  1. D A K A R A N D R O

    I D U S E R G R O U P Introduction to Type-Safe Builders: Create a DSL in Kotlin
  2. Android, Kotlin, Java, Python and other stuff Hello! I Am

    Rygel Louv GitHub: @rygelouv Twitter: @rygellouv Medium: @rygel
  3. “DSLs are small languages, focused on a particular aspect of

    a software system. You can't build a whole program with a DSL, but you often use multiple DSLs in a system mainly written in a general purpose language” “ Martin Fowler
  4. External Internal Particular form of API in a host general

    purpose language Parsed independently of the host general purpose language Two types of DSL
  5. Build a DSL in Kotlin Extension Functions Use of lambdas

    outside of parenthesis Lambdas with Receivers Scope Control with @DslMarker Infix functions
  6. When or where should I create a DSL ? “A

    good place to use DSLs could be a configuration class or a library interface where the user doesn’t have to be aware of the models.” Fré Dumazy
  7. 1 ---> Set as your DLS should look like 2

    ---> Create function with lambda as parameter 3 ---> Use that function with lambda outside of parentheses 4 ---> Get rid of the "it" by changing the lambda block into a lambda with receiver 4' ---> We can one-line the expression using apply 5 ---> In order to use val and have proper data class, setup Builder Pattern for those data class 6 ---> Move Object creation functions in model class Builder 7 ---> List of Object ? Create a collection object in the builder change the function to be an "add" of item to the collection 8 ---> Want to change the collection style ? Create helper class. Subclass of list (of the object we want to create) 9 ---> Protect the DSL safety by scoping it with @DslMarker based annotation Raw steps to build our DSL