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)

D4b7a3e2ed10f86e0b52498713ba2601?s=128

Ubiratan Soares

April 27, 2018
Tweet

Transcript

  1. 2.
  2. 3.
  3. 9.

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

    } div { +"Ho!" span { +"Lets go!" } } } } https://github.com/Kotlin/kotlinx.html
  4. 11.
  5. 12.
  6. 13.
  7. 17.

    // 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
  8. 19.

    typealias Fee = Float sealed class Tax { class FederalTax(val

    percent: Fee) : Tax() object Free : Tax() }
  9. 20.

    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 }
  10. 21.

    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 }
  11. 24.

    class Extractor { infix fun firstLetter(target: String) = target[0].toString() }

    val k = Extractor() firstLetter "Kotlin" NO PUNCTUATION!
  12. 27.
  13. 31.

    class Chainer(…) { init { initials += seed.first().toString() } infix

    fun and(another: String) = Chainer(initials, another)
  14. 32.

    class Chainer(…) { init { initials += seed.first().toString() } infix

    fun and(another: String) = Chainer(initials, another)
  15. 33.

    class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  16. 34.

    class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  17. 35.

    class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  18. 36.

    class Chainer(…) { infix fun joinedWith(option: Joiner) = initials.reduce {

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  19. 44.

    val calendar by lazy { Calendar.getInstance() } fun Date.tomorrow(): Date

    { calendar.time = this calendar.add(Calendar.DATE, 1) return calendar.time }
  20. 45.

    val calendar by lazy { Calendar.getInstance() } fun Date.tomorrow(): Date

    { calendar.time = this calendar.add(Calendar.DATE, 1) return calendar.time }
  21. 46.

    fun Date.yesterday(): Date { … } fun Date.before(some: Date): Boolean

    { … } fun Date.after(some: Date): Boolean { … } fun Date.isHolyday(): Boolean { … } fun Date.iso8601String(): String { … }
  22. 48.

    typealias IntPair = Pair<Int, Int> operator fun Date.plus(args: IntPair): Date

    { calendar.time = this calendar.add(args.first, args.second) return calendar.time }
  23. 49.

    typealias IntPair = Pair<Int, Int> operator fun Date.minus(args: IntPair): Date

    { calendar.time = this calendar.add(args.first, -args.second) return calendar.time }
  24. 50.

    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>
  25. 51.

    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()
  26. 52.

    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()
  27. 53.

    val now = Date() val past = now - 2.months

    val future = now + 15.days NO MORE PARENTHESIS !!!
  28. 55.

    fun x(lambda: () !" Unit) { lambda() } fun y(lambda:

    () !" Int) = lambda() val x: () !" Int = { TODO() } val result = x()
  29. 56.

    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)
  30. 57.

    // 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))
  31. 58.

    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()
  32. 59.

    fun receive(block: Receiver.() !" Unit) { val r = Receiver(data

    = 1) block(r) // r.block() is exactly the same } receive { println(data) // 1 }
  33. 60.

    fun receive(block: Receiver.() !" Unit) { val r = Receiver(data

    = 1) block(r) // r.block() is exactly the same } receive { println(data) // 1 }
  34. 61.
  35. 63.

    fun main(args: Array<String>) { val starWars = query { allFilms

    { films { title director releaseDate } } } }
  36. 65.

    val starWars = query { #$ TODO } fun query():

    String { #$ Something here return "query { ${ #$ Something here } }" }
  37. 66.

    val starWars = query { #$ TODO } fun query(build:

    FilmsConnection.() -> Unit): String { val connection = FilmsConnection() connection.build() return "query { ${connection.block()} }" }
  38. 67.

    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()} }" }
  39. 69.

    class FilmsConnection { private val films = Films() fun allFilms(build:

    Films.() !" Unit) = films.build() fun block() = "allFilms { ${films.block()} }" }
  40. 70.

    class FilmsConnection { private val films = Films() fun allFilms(build:

    Films.() -> Unit) = films.build() fun block() = "allFilms { ${films.block()} }" }
  41. 71.

    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()} }" }
  42. 73.

    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" } }
  43. 74.

    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" } }
  44. 75.

    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" } }
  45. 76.

    class Film { fun block() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } val releaseDate: String get() { … } private companion object { … } }
  46. 77.

    class Film { fun block() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } val releaseDate: String get() { … } private companion object { … } }
  47. 78.

    fun main(args: Array<String>) { val starWars = query { allFilms

    { films { title director releaseDate } } } println(starWars) // query { allFilms { films { title director releaseDate } } } }
  48. 79.
  49. 80.

    // Plain old mockWebServer val server = MockWebServer() val response

    = MockResponse().apply { setResponseCode(503) setBody("Ops!") } server.enqueue(response) server.start()
  50. 81.

    class MockResponseBuilder( #$ Aliases var code: Int = 0, var

    response: String? = null) { fun mockResponse() = MockResponse().apply { setResponseCode(code) setBody(response) } }
  51. 82.

    class QueueBuilder { val mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: MockResponseBuilder.()

    !" Unit) { val builder = MockResponseBuilder() builder.setup() mocks.add(builder.mockResponse()) } }
  52. 83.

    typealias BuildMock = MockResponseBuilder.() !" Unit class QueueBuilder { val

    mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: BuildMock) = MockResponseBuilder().run { setup() mocks.add(mockResponse()) } }
  53. 84.

    typealias BuildMock = MockResponseBuilder.() !" Unit class QueueBuilder { val

    mocks = mutableListOf<MockResponse>() fun enqueueMock(setup: BuildMock) = MockResponseBuilder().run { setup() mocks.add(mockResponse()) } }
  54. 86.

    typealias BuildQueue = QueueBuilder.() !" Unit fun newServer(setup: BuildQueue): MockWebServer

    = with(MockWebServer()) { QueueBuilder().run { setup() mocks.forEach { enqueue(it) } } return this }
  55. 87.

    typealias BuildQueue = QueueBuilder.() !" Unit fun newServer(setup: BuildQueue): MockWebServer

    = with(MockWebServer()) { QueueBuilder().run { setup() mocks.forEach { enqueue(it) } } return this }
  56. 88.

    val server = newServer { enqueueMock { code = 200

    response = "OK" } } server.start()
  57. 89.
  58. 91.

    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 !
  59. 93.

    UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy

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