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

Roll Your Own DSL with Kotlin (Lightning Talk)

Miguel Beltran
November 04, 2017
150

Roll Your Own DSL with Kotlin (Lightning Talk)

Domain specific languages (DSL) are everywhere. Gradle files, the Anko library or even SQL use their own DSL. They make interacting with your product easier. And thanks to Kotlin awesome features you can create your own DSL too! In this lightning talk I will show you how to get started and create your first DSL to build a UI component.

Miguel Beltran

November 04, 2017
Tweet

Transcript

  1. Roll your own DSL with Kotlin A lightning talk by

    Miquel Beltran Android Developer @ Nebenan.de @Miqubel
  2. // Old School Java Style val ratingView = RatingView() ratingView.setStars(3)

    ratingView.setMaxStars(5) // Kotlin DSL Style rating { initial = 3 maximum = 5 } @Miqubel
  3. // Creating our DSL fun rating(func:() -> Unit) // Using

    our DSL rating { initial = 3 maximum = 5 } @Miqubel
  4. // Creating our DSL fun rating(func: RatingDsl.() -> Unit) //

    Using our DSL rating { initial = 3 maximum = 5 } @Miqubel
  5. // Creating our DSL fun rating(func: RatingDsl.() -> Unit) class

    RatingDsl(var initial: Int = 1, var maximum: Int = 5) // Using our DSL rating { initial = 3 maximum = 5 } @Miqubel
  6. // Creating our DSL fun rating(func: RatingDsl.() -> Unit) =

    RatingDsl().apply { func() } class RatingDsl(var initial: Int = 1, var maximum: Int = 5) // Using our DSL rating { initial = 3 maximum = 5 } @Miqubel
  7. // Creating our DSL fun rating(func: RatingDsl.() -> Unit) =

    RatingDsl() .apply { func() } .build() class RatingDsl(var initial: Int = 1, var maximum: Int = 5) { fun build(): RatingView { return RatingView().apply { setStars(initial) setMaxStars(maximum) } } } // Using our DSL rating { initial = 3 maximum = 5 } @Miqubel
  8. Thanks! If you would be interested in a full length

    talk about this, let me know! @Miqubel