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

DSLs in a Kotlin Way - V2

Ubiratan Soares
July 21, 2018
150

DSLs in a Kotlin Way - V2

Presentation about Kotlin machinery for DSL grammars. Updated version for a previous talk.

Oferred at the following events

- The Developers Conference, Kotlin Track (July / 2018)

Ubiratan Soares

July 21, 2018
Tweet

Transcript

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

    } div { +"Ho!" span { +"Lets go!" } } } } https://github.com/Kotlin/kotlinx.html
  2. class Chainer(…) { init { initials += seed.first().toString() } infix

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

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

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

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

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

    previous, letter !" val next = when (option) { is noPunctuaction !" letter is dots !" "$letter." } "$previous$next" }
  8. val items = mutableListOf(1, 2, 3) items += 4 /#$

    * Adds the specified [element] to this mutable collection. %& @kotlin.internal.InlineOnly public inline operator fun <T> MutableCollection<in T>.plusAssign(element: T) { this.add(element) }
  9. operator fun Date.plus(args: IntPair): Date { calendar.time = this calendar.add(args.first,

    args.second) return calendar.time } operator fun Date.minus(args: IntPair): Date { calendar.time = this calendar.add(args.first, -args.second) return calendar.time }
  10. operator fun Date.plus(args: IntPair): Date { calendar.time = this calendar.add(args.first,

    args.second) return calendar.time } operator fun Date.minus(args: IntPair): Date { calendar.time = this calendar.add(args.first, -args.second) return calendar.time }
  11. fun Int.days() = Calendar.DAY_OF_YEAR to this fun Int.months() = Calendar.MONTH

    to this val atPast = Date() - 2.months() val atFuture = Date() + 15.days()
  12. val past = Date() - 2.months val future = Date()

    + 15.days val Int.days: IntPair get() = Calendar.DAY_OF_YEAR to this val Int.months: IntPair get() = Calendar.MONTH to this
  13. val toSpan = SpannableStringBuilder() val start = toSpan.length toSpan.append("First Part")

    toSpan.setSpan( UnderlineSpan(), start, toSpan.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) toSpan.setSpan( StyleSpan(android.graphics.Typeface.BOLD), start, toSpan.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) toSpan.append("not bold or underlined")
  14. fun span(given: CharSequence, span: Any): SpannableString { val spannable =

    if (given is String) SpannableString(given) else given as? SpannableString ?: throw CannotBeSpanned return spannable.apply { setSpan(span, 0, length, SPAN_EXCLUSIVE_EXCLUSIVE) } } object CannotBeSpanned : IllegalArgumentException( "Cannot apply span. Should be String or SpannableString" )
  15. // Add more hooks to same span() function fun italic(given:

    CharSequence) = span(given, StyleSpan(Typeface.ITALIC)) fun underline(given: CharSequence) = span(given, UnderlineSpan()) fun bold(given: CharSequence) = span(given, StyleSpan(Typeface.BOLD))
  16. fun x(lambda: () !" Unit) { lambda() } fun y(lambda:

    () !" Int) = lambda() val x: () !" Int = { TODO() } val result = x()
  17. 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)
  18. 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 val addOne: Receiver.() !" Int = { data + 1 } val two = addOne(Receiver(1)) val twoAgain = Receiver(1).addOne()
  19. fun receive(block: Receiver.() !" Unit) { val r = Receiver(data

    = 1) block(r) // r.block() is exactly the same } receive { println(data) // 1 }
  20. val starWars = query { allFilms { film { title

    director } } } println(starWars) > query { allFilms { film { title director } } }
  21. val starWars = query { '( TODO } fun query():

    String { return "query { ${ '( Something here } }" }
  22. val starWars = query { '( TODO } fun query(setup:

    AllFilmsBlock.() !" String) = "query { ${setup(AllFilmsBlock())} }"
  23. val starWars = query { '( TODO } fun query(setup:

    AllFilmsBlock.() !" String) = "query { ${setup(AllFilmsBlock())} }"
  24. val starWars = query { '( TODO } fun query(setup:

    AllFilmsBlock.() !" String) = "query { ${setup(AllFilmsBlock())} }"
  25. fun query(setup: AllFilmsBlock.() !" String) = "query { ${setup(AllFilmsBlock())} }"

    val starWars = query { allFilms { // TODO } } class AllFilmsBlock { fun allFilms(setup: FilmBlock.() !" String) = "allFilms { ${setup(FilmBlock())} }" }
  26. fun query(setup: AllFilmsBlock.() !" String) = "query { ${setup(AllFilmsBlock())} }"

    val starWars = query { allFilms { // TODO } } class AllFilmsBlock { fun allFilms(setup: FilmBlock.() !" String) = "allFilms { ${setup(FilmBlock())} }" }
  27. val starWars = query { allFilms { film { }

    } } class FilmBlock { fun film(setup: FilmFields.() !" String) = with(FilmFields()) { setup() "film { ${fields()} }" } }
  28. val starWars = query { allFilms { film { }

    } } class FilmBlock { fun film(setup: FilmFields.() !" String) = with(FilmFields()) { setup() "film { ${fields()} }" } }
  29. val starWars = query { allFilms { film { }

    } } class FilmBlock { fun film(setup: FilmFields.() !" String) = with(FilmFields()) { setup() "film { ${fields()} }" } }
  30. class FilmFiels { private val picked = mutableListOf<String>() fun fields()

    = TODO() val title: String get() { picked.add(TITLE) return TITLE } }
  31. class FilmFields { val title: String get() { … }

    val director: String get() { … } private companion object { const val TITLE = "title" const val DIRECTOR = "director" } }
  32. class FilmFields { fun fields() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } private companion object { … } }
  33. class FilmFields { fun fields() = picked.distinct().joinToString(separator = " ")

    val title: String get() { … } val director: String get() { … } private companion object { … } }
  34. val starWars = query { allFilms { film { title

    director } } } println(starWars)
  35. // Plain old mockWebServer val server = MockWebServer() val response

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

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

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

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

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

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

    = with(MockWebServer()) { QueueBuilder().run { setup() mocks.forEach { enqueue(it) } } return this }
  42. // DSL based val server = newServer { enqueueMock {

    code = 200 response = "OK" } } server.start() // Plain old mockWebServer val server = MockWebServer() val response = MockResponse().apply { setResponseCode(503) setBody("Ops!") } server.enqueue(response) server.start()
  43. 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 !
  44. UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy

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