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

DSLs in a Kotlin Way

DSLs in a Kotlin Way

Presentation about Kotlin machinery for DSLs grammars.

Presented at the following events

- Kotlin Night Cascavél (April / 2018)
- GDG-SP Android Meetup #58 (June / 2018)
- Online Hangout with GDGs Ourinhos + Foz + Divinópolis (June / 2018)

Ubiratan Soares

April 27, 2018
Tweet

More Decks by Ubiratan Soares

Other Decks in Programming

Transcript

  1. val tree = createHTMLDocument().html { body { h1 { +"Hey"

    } div { +"Ho!" span { +"Lets go!" } } } } https://github.com/Kotlin/kotlinx.html
  2. // Can be used with function literals typealias Factory =

    () !" User // Shine with Generics typealias StringTriplet = Triple<String, String, String> // Nice to abbreviate long names typealias OnPermissionResult = ActivityCompat.OnRequestPermissionsResultCallback
  3. typealias Fee = Float sealed class Tax { class FederalTax(val

    percent: Fee) : Tax() object Free : Tax() }
  4. typealias Fee = Float sealed class Tax { class FederalTax(val

    percent: Fee) : Tax() object Free : Tax() } fun evaluate(incoming: Tax) = when (incoming) { is Tax.FederalTax !" incoming.percent is Tax.Free !" 0.0f }
  5. typealias Fee = Float sealed class Tax class FederalTax(val percent:

    Fee) : Tax() object Free : Tax() fun evaluate(incoming: Tax) = when (incoming) { is FederalTax !" incoming.percent is Free !" 0.0f }
  6. class Extractor { infix fun firstLetter(target: String) = target[0].toString() }

    val k = Extractor() firstLetter "Kotlin" NO PUNCTUATION!
  7. class Chainer(…) { init { initials += seed.first().toString() } infix

    fun and(another: String) = Chainer(initials, another)
  8. class Chainer(…) { init { initials += seed.first().toString() } infix

    fun and(another: String) = Chainer(initials, another)
  9. class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  10. class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  11. class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  12. class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  13. val calendar by lazy { Calendar.getInstance() } fun Date.tomorrow(): Date

    { calendar.time = this calendar.add(Calendar.DATE, 1) return calendar.time }
  14. val calendar by lazy { Calendar.getInstance() } fun Date.tomorrow(): Date

    { calendar.time = this calendar.add(Calendar.DATE, 1) return calendar.time }
  15. fun Date.yesterday(): Date { … } fun Date.before(some: Date): Boolean

    { … } fun Date.after(some: Date): Boolean { … } fun Date.isHolyday(): Boolean { … } fun Date.iso8601String(): String { … }
  16. typealias IntPair = Pair<Int, Int> operator fun Date.plus(args: IntPair): Date

    { calendar.time = this calendar.add(args.first, args.second) return calendar.time }
  17. typealias IntPair = Pair<Int, Int> operator fun Date.minus(args: IntPair): Date

    { calendar.time = this calendar.add(args.first, -args.second) return calendar.time }
  18. fun Int.months() = Calendar.MONTH to this val atPast = Date()

    - 2.months() fun Int.days() = Calendar.DAY_OF_YEAR to this val atFuture = Date() + 15.days() typealias IntPair = Pair<Int, Int>
  19. fun Int.days() = Calendar.DAY_OF_YEAR to this val Int.days: IntPair get()

    = days() fun Int.months() = Calendar.MONTH to this val Int.months: IntPair get() = months()
  20. fun Int.days() = Calendar.DAY_OF_YEAR to this val Int.days: IntPair get()

    = days() fun Int.months() = Calendar.MONTH to this val Int.months: IntPair get() = months()
  21. val now = Date() val past = now - 2.months

    val future = now + 15.days NO MORE PARENTHESIS !!!
  22. fun x(lambda: () !" Unit) { lambda() } fun y(lambda:

    () !" Int) = lambda() val x: () !" Int = { TODO() } val result = x()
  23. val add = fun(a: Int, b: Int) = a +

    b fun calculate(func: (Int, Int) !" Int) { func.invoke(2,2) } // Trailling Notation calculate { a, b !" a + b } // Normal notation calculate(add)
  24. // Lambdas are just another representation for // functions; they

    are not DECLARED the same way // as function types val add = fun(a: Int, b: Int) = a + b val subtract: (Int, Int) !" Int = { a, b !" a - b } but passed / used as expressions as well fun report(operation: (Int, Int) !" Int) = println(operation.invoke(2, 2))
  25. class Receiver(val data: Int) // Kotlin allows us to add

    an extension function // literal to a type. Such lambda acquires the properties // of non-static method in the context class val addOne: Receiver.() !" Int = { data + 1 } val two = addOne(Receiver(1)) val twoAgain = Receiver(1).addOne()
  26. fun receive(block: Receiver.() !" Unit) { val r = Receiver(data

    = 1) block(r) // r.block() is exactly the same } receive { println(data) // 1 }
  27. fun receive(block: Receiver.() !" Unit) { val r = Receiver(data

    = 1) block(r) // r.block() is exactly the same } receive { println(data) // 1 }
  28. fun main(args: Array<String>) { val starWars = query { allFilms

    { films { title director releaseDate } } } }
  29. val starWars = query { #$ TODO } fun query():

    String { #$ Something here return "query { ${ #$ Something here } }" }
  30. val starWars = query { #$ TODO } fun query(build:

    FilmsConnection.() -> Unit): String { val connection = FilmsConnection() connection.build() return "query { ${connection.block()} }" }
  31. val starWars = query { #$ TODO } class FilmsConnection

    { fun block() = "allFilms { #$ Something here }" } fun query(build: FilmsConnection.() !" Unit): String { val connection = FilmsConnection() connection.build() return "query { ${connection.block()} }" }
  32. class FilmsConnection { private val films = Films() fun allFilms(build:

    Films.() !" Unit) = films.build() fun block() = "allFilms { ${films.block()} }" }
  33. class FilmsConnection { private val films = Films() fun allFilms(build:

    Films.() -> Unit) = films.build() fun block() = "allFilms { ${films.block()} }" }
  34. class FilmsConnection { private val films = Films() fun allFilms(build:

    Films.() -> Unit) = films.build() fun block() = "allFilms { ${films.block()} }" } class Films { private val film = Film() fun films(build: Film.() -> Unit) = film.build() fun block() = "films { ${film.block()} }" }
  35. class Film { private val picked = mutableListOf<String>() fun block()

    = TODO() val title: String get() { picked.add(TITLE) return TITLE } private companion object { const val TITLE = "title" } }
  36. class Film { private val picked = mutableListOf<String>() fun block()

    = TODO() val title: String get() { picked.add(TITLE) return TITLE } private companion object { const val TITLE = "title" } }
  37. class Film { val title: String get() { … }

    val director: String get() { … } val releaseDate: String get() { … } private companion object { const val TITLE = "title" const val DIRECTOR = "director" const val RELEASE_DATE = "releaseDate" } }
  38. class Film { fun block() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } val releaseDate: String get() { … } private companion object { … } }
  39. class Film { fun block() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } val releaseDate: String get() { … } private companion object { … } }
  40. fun main(args: Array<String>) { val starWars = query { allFilms

    { films { title director releaseDate } } } println(starWars) // query { allFilms { films { title director releaseDate } } } }
  41. // Plain old mockWebServer val server = MockWebServer() val response

    = MockResponse().apply { setResponseCode(503) setBody("Ops!") } server.enqueue(response) server.start()
  42. class MockResponseBuilder( #$ Aliases var code: Int = 0, var

    response: String? = null) { fun mockResponse() = MockResponse().apply { setResponseCode(code) setBody(response) } }
  43. class QueueBuilder { val mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: MockResponseBuilder.()

    !" Unit) { val builder = MockResponseBuilder() builder.setup() mocks.add(builder.mockResponse()) } }
  44. typealias BuildMock = MockResponseBuilder.() !" Unit class QueueBuilder { val

    mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: BuildMock) = MockResponseBuilder().run { setup() mocks.add(mockResponse()) } }
  45. typealias BuildMock = MockResponseBuilder.() !" Unit class QueueBuilder { val

    mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: BuildMock) = MockResponseBuilder().run { setup() mocks.add(mockResponse()) } }
  46. typealias BuildQueue = QueueBuilder.() !" Unit fun newServer(setup: BuildQueue): MockWebServer

    = with(MockWebServer()) { QueueBuilder().run { setup() mocks.forEach { enqueue(it) } } return this }
  47. typealias BuildQueue = QueueBuilder.() !" Unit fun newServer(setup: BuildQueue): MockWebServer

    = with(MockWebServer()) { QueueBuilder().run { setup() mocks.forEach { enqueue(it) } } return this }
  48. val server = newServer { enqueueMock { code = 200

    response = "OK" } } server.start()
  49. CONCLUSIONS • DSLs are fun (with no pun) • DSL-building

    offer great insights over Kotlin features! • DSLs should work to improve an existing domain, not replace it • Design your own DSLs for fun and profit !
  50. UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy

    Google Expert for Android and Kotlin Teacher, speaker, etc, etc