Roll Your Own DSL with Kotlin (Lightning Talk)

72ffb135de71bef2c4a11961634edc6a?s=47 Miguel Beltran
November 04, 2017
110

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.

72ffb135de71bef2c4a11961634edc6a?s=128

Miguel Beltran

November 04, 2017
Tweet

Transcript

  1. 1.

    Roll your own DSL with Kotlin A lightning talk by

    Miquel Beltran Android Developer @ Nebenan.de @Miqubel
  2. 6.

    // Old School Java Style val ratingView = RatingView() ratingView.setStars(3)

    ratingView.setMaxStars(5) // Kotlin DSL Style rating { initial = 3 maximum = 5 } @Miqubel
  3. 10.

    // Creating our DSL fun rating(func:() -> Unit) // Using

    our DSL rating { initial = 3 maximum = 5 } @Miqubel
  4. 11.

    // Creating our DSL fun rating(func: RatingDsl.() -> Unit) //

    Using our DSL rating { initial = 3 maximum = 5 } @Miqubel
  5. 12.

    // 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. 13.

    // 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. 14.

    // 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. 15.

    Thanks! If you would be interested in a full length

    talk about this, let me know! @Miqubel