Slide 1

Slide 1 text

DSLs IN A KOTLIN WAY Ubiratan Soares June / 2018

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

INTERNAL LANGUAGE EXTERNAL LANGUAGE

Slide 5

Slide 5 text

SELECT * FROM accounts WHERE id=12345

Slide 6

Slide 6 text

SELECT * FROM accounts WHERE id=12345 " "

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

--- punctuation --- overhead +++ grammar +++ structure

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

TYPE ALIASES

Slide 15

Slide 15 text

typealias UserId = String fun findUser(by: UserId) { TODO() }

Slide 16

Slide 16 text

typealias Seconds = Int typealias Duration = Int fun ellapsed(amount: Seconds): Duration { TODO() }

Slide 17

Slide 17 text

// Can be used with function literals typealias Factory = () !" User // Shine with Generics typealias StringTriplet = Triple // Nice to abbreviate long names typealias OnPermissionResult = ActivityCompat.OnRequestPermissionsResultCallback

Slide 18

Slide 18 text

SEALED CLASSES

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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 }

Slide 21

Slide 21 text

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 }

Slide 22

Slide 22 text

INFIX NOTATION

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 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 34

Slide 34 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 35

Slide 35 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 36

Slide 36 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 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

EXTENSIONS

Slide 41

Slide 41 text

fun Boolean.nor(another: Boolean) = or(another).not() val nored = true.nor(false)

Slide 42

Slide 42 text

infix fun Boolean.nand(some: Boolean) = and(value).not()

Slide 43

Slide 43 text

infix fun Boolean.nand(some: Boolean) = and(value).not() val nanded = false nand true

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

fun Date.yesterday(): Date { … } fun Date.before(some: Date): Boolean { … } fun Date.after(some: Date): Boolean { … } fun Date.isHolyday(): Boolean { … } fun Date.iso8601String(): String { … }

Slide 47

Slide 47 text

OPERATOR OVERLOADS

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

val now = Date() val past = now - 2.months val future = now + 15.days NO MORE PARENTHESIS !!!

Slide 54

Slide 54 text

LAMBDAS + RECEIVERS

Slide 55

Slide 55 text

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

Slide 56

Slide 56 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 57

Slide 57 text

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

Slide 58

Slide 58 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 class val addOne: Receiver.() !" Int = { data + 1 } val two = addOne(Receiver(1)) val twoAgain = Receiver(1).addOne()

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

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

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

fun main(args: Array) { val starWars = query { allFilms { films { title director releaseDate } } } }

Slide 64

Slide 64 text

val starWars = query { #$ TODO }

Slide 65

Slide 65 text

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

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

class Film { fun block() = TODO() }

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

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

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

fun main(args: Array) { val starWars = query { allFilms { films { title director releaseDate } } } println(starWars) // query { allFilms { films { title director releaseDate } } } }

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

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

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

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

Slide 83

Slide 83 text

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

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

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

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

val server = newServer { enqueueMock { code = 200 response = "OK" } } server.start()

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

FINAL
 REMARKS

Slide 91

Slide 91 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 92

Slide 92 text

CHECK THESE ONES ! https://github.com/kotlintest/kotlintest https://github.com/JetBrains/Exposed https://github.com/Kotlin/anko Anko Kotlintest Exposed

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

https://speakerdeck.com/ubiratansoares

Slide 95

Slide 95 text

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