Slide 1

Slide 1 text

DSLs IN A KOTLIN WAY Ubiratan Soares July / 2018 VERSION 2.0

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

SELECT * FROM accounts WHERE id=12345

Slide 4

Slide 4 text

SELECT * FROM accounts WHERE id=12345 " "

Slide 5

Slide 5 text

String sql = SQLiteQueryBuilder .select("*") .from("accounts") .where("id=12345") .toString(); https://github.com/alexfu/SQLiteQueryBuilder

Slide 6

Slide 6 text

Hey!!"h1>
Ho!Lets go!!"span> !"div> !"body> !"html>

Slide 7

Slide 7 text

val tree = createHTMLDocument().html { body { h1 { +"Hey" } div { +"Ho!" span { +"Lets go!" } } } } https://github.com/Kotlin/kotlinx.html

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Disclaimer : Strategic jump

Slide 12

Slide 12 text

Type Aliases Sealed Classes Extension Functions Extension Properties ETC

Slide 13

Slide 13 text

VERSION 1.0

Slide 14

Slide 14 text

INFIX NOTATION

Slide 15

Slide 15 text

class Extractor { fun firstLetter(target: String) = target[0].toString() } val k = Extractor().firstLetter("Kotlin")

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

object extract { infix fun firstLetterOf(target: String) = target[0].toString() }

Slide 18

Slide 18 text

object extract { infix fun firstLetterOf(target: String) = target[0].toString() } val first = extract firstLetterOf "Awesome"

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

object acronymn { infix fun from(target: String) = Chainer( initials = mutableListOf(), seed = target ) }

Slide 21

Slide 21 text

object acronymn { infix fun from(target: String) = Chainer( initials = mutableListOf(), seed = target ) }

Slide 22

Slide 22 text

class Chainer( private val initials: MutableList, seed: String) { init { initials += seed.first().toString() }

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

sealed class Joiner object noPunctuaction : Joiner() object dots : Joiner()

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

val dsl = acronymn from "Domain" and "Specific" and "Language" joinedWith noPunctuaction //DSL

Slide 31

Slide 31 text

val dsl = acronymn from "Domain" and "Specific" and "Language" joinedWith dots //D.S.L

Slide 32

Slide 32 text

OPERATOR OVERLOADS

Slide 33

Slide 33 text

val items = mutableListOf(1, 2, 3) items += 4

Slide 34

Slide 34 text

val items = mutableListOf(1, 2, 3) items += 4 /#$ * Adds the specified [element] to this mutable collection. %& @kotlin.internal.InlineOnly public inline operator fun MutableCollection.plusAssign(element: T) { this.add(element) }

Slide 35

Slide 35 text

typealias IntPair = Pair val calendar by lazy { Calendar.getInstance() }

Slide 36

Slide 36 text

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 }

Slide 37

Slide 37 text

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 }

Slide 38

Slide 38 text

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()

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

A The problem like with spannables on Android

Slide 42

Slide 42 text

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")

Slide 43

Slide 43 text

operator fun SpannableString.plus(s: String) = SpannableString(TextUtils.concat(this, s)) operator fun SpannableString.plus(s: SpannableString) = SpannableString(TextUtils.concat(this, s))

Slide 44

Slide 44 text

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" )

Slide 45

Slide 45 text

// 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))

Slide 46

Slide 46 text

val spanned = "normal" + bold("bold") + italic("italic") label.setText(spanned)

Slide 47

Slide 47 text

LAMBDAS + RECEIVERS

Slide 48

Slide 48 text

fun x(lambda: () !" Unit) { lambda() } fun y(lambda: () !" Int) = lambda() val x: () !" Int = { TODO() } val result = x()

Slide 49

Slide 49 text

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)

Slide 50

Slide 50 text

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()

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

https://graphql.org/swapi-graphql/

Slide 54

Slide 54 text

val starWars = query { allFilms { film { title director } } } println(starWars) > query { allFilms { film { title director } } }

Slide 55

Slide 55 text

val starWars = query { '( TODO }

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

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

Slide 62

Slide 62 text

val starWars = query { allFilms { film { // TODO } } }

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

class FilmFiels { private val picked = mutableListOf() fun fields() = TODO() val title: String get() { picked.add(TITLE) return TITLE } }

Slide 67

Slide 67 text

class FilmFields { val title: String get() { … } val director: String get() { … } private companion object { const val TITLE = "title" const val DIRECTOR = "director" } }

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

val starWars = query { allFilms { film { title director } } } println(starWars)

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

// Plain old mockWebServer val server = MockWebServer() val response = MockResponse().apply { setResponseCode(503) setBody("Ops!") } server.enqueue(response) server.start()

Slide 73

Slide 73 text

class MockResponseBuilder( '( Aliases var code: Int = 0, var response: String? = null) { fun mockResponse() = MockResponse().apply { setResponseCode(code) setBody(response) } }

Slide 74

Slide 74 text

class QueueBuilder { val mocks = mutableListOf() fun enqueueMock(setup: MockResponseBuilder.() !" Unit) { val builder = MockResponseBuilder() builder.setup() mocks.add(builder.mockResponse()) } }

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

typealias BuildQueue = QueueBuilder.() !" Unit fun newServer(setup: BuildQueue): MockWebServer = with(MockWebServer()) { '( ???? return this }

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text

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

Slide 80

Slide 80 text

// 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()

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

FINAL
 REMARKS

Slide 83

Slide 83 text

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 !

Slide 84

Slide 84 text

https://speakerdeck.com/ubiratansoares

Slide 85

Slide 85 text

UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy Google Expert for Android and Kotlin Teacher, speaker, etc, etc

Slide 86

Slide 86 text

THANK YOU @ubiratanfsoares ubiratansoares.github.io https://br.linkedin.com/in/ubiratanfsoares