SlideShare a Scribd company logo
KOTLIN -
DSL
About me :)
‣ Roque Buarque Junior
‣ Brazilian
‣ Android Engineer
‣ Berlin - Germany
‣ Sharenow
‣ @roqbjr
KOTLIN - DSL
WHAT YOU WILL SEE?
▸What is DSL?
▸DSL Examples
▸Kotlin features to build a DSL
▸Code
▸Code
▸And more CODE
KOTLIN - DSL
KOTLIN IN ACTION
▸Chapter 11 - DSL Construction
A DOMAIN-SPECIFIC
LANGUAGE (DSL) IS A COMPUTER
LANGUAGE SPECIALIZED TO A
PARTICULAR
APPLICATION DOMAIN. THIS IS IN
CONTRAST TO A GENERAL-
PURPOSE LANGUAGE (GPL),
WHICH IS BROADLY APPLICABLE
ACROSS DOMAINS. From Wikipedia
KOTLIN - DSL
WH
Y?
KOTLIN - DSL
val list = mutableListOf("A", "B", "C").toList()
val list = buildList {
add("A")
add("B")
add("C")
}
KOTLIN - DSL
HIGHER-ORDER FUNCTIONS AND
LAMBDAS
▸Store in variables and data structures
▸Pass as argument to and return from other function
A higher-order function is a function that takes functions as parameters, or returns a function.
KOTLIN - DSL
class Person {
lateinit var name: String
lateinit var email: String
}
KOTLIN - DSL
class Person {
lateinit var name: String
lateinit var email: String
}
val person = Person()
person.name = "Roque"
person.email = "roque@email.com"
SCOP
E
FUNCT
IONS
KOTLIN - DSL
class Person {
lateinit var name: String
lateinit var email: String
}
Person()
.apply {
this.name = "Roque"
this.email = "roque@email.com"
}
KOTLIN - DSL
class Person {
lateinit var name: String
lateinit var email: String
}
Person()
.apply {
name = "Roque"
email = "roque@email.com"
}
KOTLIN - DSL
val helloWorld = "Hello".apply {
"$this World"
}
Hello
KOTLIN - DSL
Person()
.apply {
name = "Roque"
email = "roque@email.com"
}
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
KOTLIN - DSL
Person()
.let {
it.name = "Roque"
it.email = "roque@email.com"
}
KOTLIN - DSL
val helloWorld = "Hello".let {
"$it World"
}
Hello World
KOTLIN - DSL
Person()
.let {
it.name = "Roque"
it.email = "roque@email.com"
}
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
KOTLIN - DSL
fun helloWorld(block: () -> Unit) {
println("Hello World")
block()
}
helloWorld{ }
Hello World
KOTLIN - DSL
fun helloWorld(block: (String) -> Unit) {
println("Hello")
block("World")
}
helloWorld{
print(it)
}
Hello
World
KOTLIN - DSL
fun helloWorld(block: String.(String) -> Unit) {
block(“Hello”, “World”)
}
helloWorld{
print(“$this $it”)
}
Hello World
KOTLIN - DSL
fun <T> T.helloWorld(block: T.() -> Unit) {
block(this)
}
"Hello".helloWorld {
print(this)
}
Hello
KOTLIN - DSL
fun <T, R> T.helloWorld(block: T.() -> R) : R {
return block(this)
}
val helloWorld = "Hello".helloWorld {
"$this World"
}
print(helloWorld)
Hello World
KOTLIN - DSL
HTML
<table>
<tr>
<td> cell </td>
</tr>
</table>
KOTLIN - DSL
HTML
"<table>
<tr>
<td> cell </td>
</tr>
</table>"
KOTLIN - DSL
HTML
“<table>
<tr>
<td> cell </td>
</tr>
</table>"
createHTML().
table {
tr {
td { +”cell” }
}
}
https://github.com/Kotlin/kotlinx.html
KOTLIN - DSL
SQL
SELECT *
FROM users
WHERE age = 18
KOTLIN - DSL
SQL
"SELECT *
FROM users
WHERE age = 18”
KOTLIN - DSL
EXPOSED - JETBRAINS
https://github.com/JetBrains/Exposed/
"SELECT *
FROM users
WHERE age = 18”
Users.select {
Users.age eq 18
}
KOTLIN - DSL
SQL
User select { age eq 18 }
INF
IX
KOTLIN - DSL
INFIX
▸Must be member function or extension function
▸Must have only a single parameter
▸The parameter must have no default value
▸The parameter must not accept varargs
▸Receiver and parameter must be specified
Functions marked with the infix keyword can also be called using the infix notation(omitting the dot and the
parentheses for the call)
KOTLIN - DSL
object User {
operator fun invoke(query: String): User {
this.query += query
return this
}
infix fun select(block: User.() -> Unit) {
User("SELECT * FROM users").block()
}
}
KOTLIN - DSL
object User {
private var query = ""
val age: User
get() = this.where("age")
val name: User
get() = this.where("name")
private fun where(field: String): User {
query+= " WHERE $field"
return this
}
infix fun eq(age: Int) {
println("$query = $age")
}
}
KOTLIN - DSL
SQL
User select { age eq 18 }
KOTLIN - DSL
SQL
User select { age eq 18 }
SELECT * FROM users WHERE age = 18
CAKE
DSL
KOTLIN - DSL
CAKE
val cake = Cooker make Cake of Chocolate and Coconut withOut
Sugar forMy Birthday
print(cake)
KOTLIN - DSL
INFIX
class Cooker {
}
KOTLIN - DSL
INFIX
class Cooker {
fun make(value: Dish)
{
. . .
}
}
Cooker().make(Cake())
KOTLIN - DSL
INFIX
class Cooker {
infix fun make(value: Dish)
{
. . .
}
}
Cooker() make Cake()
KOTLIN - DSL
INFIX
object Cooker {
infix fun make(value: Dish)
{
. . .
}
}
Cooker make Cake()
SEALED
CLASS
KOTLIN - DSL
SEALED CLASS
▸Is abstract by itself, cannot be instantiated
▸Not allowed to have non-private constructors (their
constructors are private by default).
Sealed classes are used for representing restricted class hierarchies, when a value can have one of the
types from limited set, but cannot have any other type.
KOTLIN - DSL
SEALED CLASSES
class Ingredients{
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients{
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients{
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients{
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
}
private fun convertFlavorToString(ing: Ingridient): String {
return when (ing) {
is Ingredients.Chocolate -> "Chocolate"
is Ingredients.Coconut -> "Coconut"
}
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients{
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
}
* when expression must be exhaustive
private fun convertFlavorToString(ing: Ingridient): String {
return when (ing) {
is Ingredients.Chocolate -> "Chocolate"
is Ingredients.Coconut -> "Coconut"
}
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients{
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
}
private fun convertFlavorToString(ing: Ingridient): String {
return when (ing) {
is Ingredients.Chocolate -> "Chocolate"
is Ingredients.Coconut -> "Coconut"
is Ingredients.Sugar -> "Sugar"
}
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
private fun convertFlavorToString(ing: Ingridient): String {
return when (ing) {
is Ingredients.Chocolate -> "Chocolate"
is Ingredients.Coconut -> "Coconut"
is Ingredients.Sugar -> "Sugar"
}
}
KOTLIN - DSL
SEALED CLASSES
sealed class Ingredients
object Chocolate : Ingredients()
object Coconut : Ingredients()
object Sugar : Ingredients()
private fun convertFlavorToString(ing: Ingridient): String {
return when (ing) {
is Chocolate -> "Chocolate"
is Coconut -> "Coconut"
is Sugar -> "Sugar"
}
}
KOTLIN - DSL
SEALED CLASSES - SMART CASTING
sealed class VehicleState
object Empty : VehicleState()
data class Success(val vehicles: List<Vehile>) : VehicleState()
data class Error(error: Throwable) : VehicleState()
data class Loading(isLoading: Boolean) : VehicleState()
KOTLIN - DSL
SEALED CLASSES - SMART CASTING
sealed class VehicleState
object Empty : VehicleState()
data class Success(val vehicles: List<Vehile>) : VehicleState()
data class Error(error: Throwable) : VehicleState()
data class Loading(isLoading: Boolean) : VehicleState()
private fun updateState(state: VehicleState) {
when (state) {
is Empty -> ...
is Success -> state.vehicles
is Error -> state.error
is Loading -> state.isLoading
}
}
KOTLIN - DSL
SEALED
CLASS
Cooker
Cake
Chocolate
Coconut
Sugar
Birthday
make
of
and
withOut
forMy
INFIX
KOTLIN - DSL
CAKE
val cake = Cooker make Cake of Chocolate and Coconut withOut
Sugar forMy Birthday
print(cake)
UNIT
TEST
KOTLIN - DSL
UNIT TEST
data class User(val name:String, var balance: Double) {
fun withDraw(value: Double){
this.balance -= value
}
}
KOTLIN - DSL
UNIT TEST
//Given
val user = User("Roque", 200.0)
//When
user.withDraw(50.0)
//Then
Truth.assertThat(user.balance).isEqualTo(150.0)
KOTLIN - DSL
UNIT TEST
given {
User("Roque", 200.0)
}.test {
withDraw(50.0)
}.assert {
Truth.assertThat(balance).isEqualTo(150.0)
}
KOTLIN - DSL
UNIT TEST
fun <T, R> T.given(block: () -> R): R {
return block(this)
}
KOTLIN - DSL
UNIT TEST
fun <T> T.test(block: T.() -> Unit): T {
block()
return this
}
KOTLIN - DSL
UNIT TEST
fun <T> T.assert(block: T.() -> Unit) {
this.block()
}
KOTLIN - DSL
UNIT TEST
given {
User("Roque", 200.0)
}.test {
withDraw(50.0)
}.assert {
balance isEquals 150.0
}
KOTLIN - DSL
UNIT TEST
infix fun<T> T.isEquals(value: T):{
Truth.assertThat(this).isEqualTo(value)
}
KOTLIN - DSL
UNIT TEST
whenever(repository.increase()).thenReturn(Counter(1))
KOTLIN - DSL
UNIT TEST
whenever(repository.increase()).thenReturn(Counter(1))
repository.increase() willReturn Counter(1)
KOTLIN - DSL
UNIT TEST
whenever(repository.increase()).thenReturn(Counter(1))
repository.increase() willReturn Counter(1)
infix fun <T> T.willReturn(value: T) {
given(this)
.willReturn(value)
}
NEXT
STEPS?
KOTLIN - DSL
NEXT STEPS
▸Find your necessity
▸Check if already exist
▸Sync with your team
▸Be creative
▸Enjoy more readable code :)
KOTLIN - DSL
SUMMARIZE
▸Infix notation
▸Sealed Class
▸Higher order functions
▸Lambda with receivers
▸Lambda parameter
▸Operator overloading
THANK
YOU!!!
Q&
A’S

More Related Content

PPTX
Oracle Database - JSON and the In-Memory Database
PPTX
Starting with JSON Path Expressions in Oracle 12.1.0.2
PDF
UKOUG Tech14 - Getting Started With JSON in the Database
PDF
R Programming: Transform/Reshape Data In R
PDF
The Ring programming language version 1.5.1 book - Part 26 of 180
PPTX
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
PDF
R Programming: Learn To Manipulate Strings In R
PDF
The Ring programming language version 1.10 book - Part 36 of 212
Oracle Database - JSON and the In-Memory Database
Starting with JSON Path Expressions in Oracle 12.1.0.2
UKOUG Tech14 - Getting Started With JSON in the Database
R Programming: Transform/Reshape Data In R
The Ring programming language version 1.5.1 book - Part 26 of 180
OakTable World 2015 - Using XMLType content with the Oracle In-Memory Column...
R Programming: Learn To Manipulate Strings In R
The Ring programming language version 1.10 book - Part 36 of 212

Similar to Kotlin dsl (20)

PDF
Sprache als Werkzeug: DSLs mit Kotlin (JAX 2020)
PPTX
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
PPTX
Create your DSL with Kotlin
PDF
Devoxx Ukraine 2018 - Kotlin DSL in under an hour
PPTX
Nice to meet Kotlin
PDF
Log cat kotlindsl
PDF
GeeCON Prague 2018 - Kotlin DSL in under an hour
PDF
JavaZone 2022 - Building Kotlin DSL.pdf
PDF
Intro to Kotlin
PDF
9054799 dzone-refcard267-kotlin
PPTX
Kotlin
PDF
2017: Kotlin - now more than ever
PDF
kotlin.pdf
PDF
Why Kotlin is your next language?
PDF
Introduction to kotlin
PPTX
Java One - Designing a DSL in Kotlin
PPTX
JUG Lausanne - Kotlin DSL
PDF
Having Fun with Kotlin Android - DILo Surabaya
PDF
Kotlin - Better Java
PDF
Kotlin @ Devoxx 2011
Sprache als Werkzeug: DSLs mit Kotlin (JAX 2020)
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Create your DSL with Kotlin
Devoxx Ukraine 2018 - Kotlin DSL in under an hour
Nice to meet Kotlin
Log cat kotlindsl
GeeCON Prague 2018 - Kotlin DSL in under an hour
JavaZone 2022 - Building Kotlin DSL.pdf
Intro to Kotlin
9054799 dzone-refcard267-kotlin
Kotlin
2017: Kotlin - now more than ever
kotlin.pdf
Why Kotlin is your next language?
Introduction to kotlin
Java One - Designing a DSL in Kotlin
JUG Lausanne - Kotlin DSL
Having Fun with Kotlin Android - DILo Surabaya
Kotlin - Better Java
Kotlin @ Devoxx 2011
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
August Patch Tuesday
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Machine learning based COVID-19 study performance prediction
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPT
Teaching material agriculture food technology
PPTX
Spectroscopy.pptx food analysis technology
PPTX
1. Introduction to Computer Programming.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Machine Learning_overview_presentation.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A comparative study of natural language inference in Swahili using monolingua...
Network Security Unit 5.pdf for BCA BBA.
August Patch Tuesday
Building Integrated photovoltaic BIPV_UPV.pdf
TLE Review Electricity (Electricity).pptx
A Presentation on Artificial Intelligence
Machine learning based COVID-19 study performance prediction
Assigned Numbers - 2025 - Bluetooth® Document
Diabetes mellitus diagnosis method based random forest with bat algorithm
Programs and apps: productivity, graphics, security and other tools
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Heart disease approach using modified random forest and particle swarm optimi...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Teaching material agriculture food technology
Spectroscopy.pptx food analysis technology
1. Introduction to Computer Programming.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Machine Learning_overview_presentation.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Ad

Kotlin dsl

  • 2. About me :) ‣ Roque Buarque Junior ‣ Brazilian ‣ Android Engineer ‣ Berlin - Germany ‣ Sharenow ‣ @roqbjr
  • 3. KOTLIN - DSL WHAT YOU WILL SEE? ▸What is DSL? ▸DSL Examples ▸Kotlin features to build a DSL ▸Code ▸Code ▸And more CODE
  • 4. KOTLIN - DSL KOTLIN IN ACTION ▸Chapter 11 - DSL Construction
  • 5. A DOMAIN-SPECIFIC LANGUAGE (DSL) IS A COMPUTER LANGUAGE SPECIALIZED TO A PARTICULAR APPLICATION DOMAIN. THIS IS IN CONTRAST TO A GENERAL- PURPOSE LANGUAGE (GPL), WHICH IS BROADLY APPLICABLE ACROSS DOMAINS. From Wikipedia KOTLIN - DSL
  • 7. KOTLIN - DSL val list = mutableListOf("A", "B", "C").toList() val list = buildList { add("A") add("B") add("C") }
  • 8. KOTLIN - DSL HIGHER-ORDER FUNCTIONS AND LAMBDAS ▸Store in variables and data structures ▸Pass as argument to and return from other function A higher-order function is a function that takes functions as parameters, or returns a function.
  • 9. KOTLIN - DSL class Person { lateinit var name: String lateinit var email: String }
  • 10. KOTLIN - DSL class Person { lateinit var name: String lateinit var email: String } val person = Person() person.name = "Roque" person.email = "roque@email.com"
  • 12. KOTLIN - DSL class Person { lateinit var name: String lateinit var email: String } Person() .apply { this.name = "Roque" this.email = "roque@email.com" }
  • 13. KOTLIN - DSL class Person { lateinit var name: String lateinit var email: String } Person() .apply { name = "Roque" email = "roque@email.com" }
  • 14. KOTLIN - DSL val helloWorld = "Hello".apply { "$this World" } Hello
  • 15. KOTLIN - DSL Person() .apply { name = "Roque" email = "roque@email.com" } public inline fun <T> T.apply(block: T.() -> Unit): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() return this }
  • 16. KOTLIN - DSL Person() .let { it.name = "Roque" it.email = "roque@email.com" }
  • 17. KOTLIN - DSL val helloWorld = "Hello".let { "$it World" } Hello World
  • 18. KOTLIN - DSL Person() .let { it.name = "Roque" it.email = "roque@email.com" } public inline fun <T, R> T.let(block: (T) -> R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block(this) }
  • 19. KOTLIN - DSL fun helloWorld(block: () -> Unit) { println("Hello World") block() } helloWorld{ } Hello World
  • 20. KOTLIN - DSL fun helloWorld(block: (String) -> Unit) { println("Hello") block("World") } helloWorld{ print(it) } Hello World
  • 21. KOTLIN - DSL fun helloWorld(block: String.(String) -> Unit) { block(“Hello”, “World”) } helloWorld{ print(“$this $it”) } Hello World
  • 22. KOTLIN - DSL fun <T> T.helloWorld(block: T.() -> Unit) { block(this) } "Hello".helloWorld { print(this) } Hello
  • 23. KOTLIN - DSL fun <T, R> T.helloWorld(block: T.() -> R) : R { return block(this) } val helloWorld = "Hello".helloWorld { "$this World" } print(helloWorld) Hello World
  • 24. KOTLIN - DSL HTML <table> <tr> <td> cell </td> </tr> </table>
  • 25. KOTLIN - DSL HTML "<table> <tr> <td> cell </td> </tr> </table>"
  • 26. KOTLIN - DSL HTML “<table> <tr> <td> cell </td> </tr> </table>" createHTML(). table { tr { td { +”cell” } } } https://github.com/Kotlin/kotlinx.html
  • 27. KOTLIN - DSL SQL SELECT * FROM users WHERE age = 18
  • 28. KOTLIN - DSL SQL "SELECT * FROM users WHERE age = 18”
  • 29. KOTLIN - DSL EXPOSED - JETBRAINS https://github.com/JetBrains/Exposed/ "SELECT * FROM users WHERE age = 18” Users.select { Users.age eq 18 }
  • 30. KOTLIN - DSL SQL User select { age eq 18 }
  • 32. KOTLIN - DSL INFIX ▸Must be member function or extension function ▸Must have only a single parameter ▸The parameter must have no default value ▸The parameter must not accept varargs ▸Receiver and parameter must be specified Functions marked with the infix keyword can also be called using the infix notation(omitting the dot and the parentheses for the call)
  • 33. KOTLIN - DSL object User { operator fun invoke(query: String): User { this.query += query return this } infix fun select(block: User.() -> Unit) { User("SELECT * FROM users").block() } }
  • 34. KOTLIN - DSL object User { private var query = "" val age: User get() = this.where("age") val name: User get() = this.where("name") private fun where(field: String): User { query+= " WHERE $field" return this } infix fun eq(age: Int) { println("$query = $age") } }
  • 35. KOTLIN - DSL SQL User select { age eq 18 }
  • 36. KOTLIN - DSL SQL User select { age eq 18 } SELECT * FROM users WHERE age = 18
  • 38. KOTLIN - DSL CAKE val cake = Cooker make Cake of Chocolate and Coconut withOut Sugar forMy Birthday print(cake)
  • 40. KOTLIN - DSL INFIX class Cooker { fun make(value: Dish) { . . . } } Cooker().make(Cake())
  • 41. KOTLIN - DSL INFIX class Cooker { infix fun make(value: Dish) { . . . } } Cooker() make Cake()
  • 42. KOTLIN - DSL INFIX object Cooker { infix fun make(value: Dish) { . . . } } Cooker make Cake()
  • 44. KOTLIN - DSL SEALED CLASS ▸Is abstract by itself, cannot be instantiated ▸Not allowed to have non-private constructors (their constructors are private by default). Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from limited set, but cannot have any other type.
  • 45. KOTLIN - DSL SEALED CLASSES class Ingredients{ }
  • 46. KOTLIN - DSL SEALED CLASSES sealed class Ingredients{ }
  • 47. KOTLIN - DSL SEALED CLASSES sealed class Ingredients{ object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() }
  • 48. KOTLIN - DSL SEALED CLASSES sealed class Ingredients{ object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() } private fun convertFlavorToString(ing: Ingridient): String { return when (ing) { is Ingredients.Chocolate -> "Chocolate" is Ingredients.Coconut -> "Coconut" } }
  • 49. KOTLIN - DSL SEALED CLASSES sealed class Ingredients{ object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() } * when expression must be exhaustive private fun convertFlavorToString(ing: Ingridient): String { return when (ing) { is Ingredients.Chocolate -> "Chocolate" is Ingredients.Coconut -> "Coconut" } }
  • 50. KOTLIN - DSL SEALED CLASSES sealed class Ingredients{ object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() } private fun convertFlavorToString(ing: Ingridient): String { return when (ing) { is Ingredients.Chocolate -> "Chocolate" is Ingredients.Coconut -> "Coconut" is Ingredients.Sugar -> "Sugar" } }
  • 51. KOTLIN - DSL SEALED CLASSES sealed class Ingredients object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() private fun convertFlavorToString(ing: Ingridient): String { return when (ing) { is Ingredients.Chocolate -> "Chocolate" is Ingredients.Coconut -> "Coconut" is Ingredients.Sugar -> "Sugar" } }
  • 52. KOTLIN - DSL SEALED CLASSES sealed class Ingredients object Chocolate : Ingredients() object Coconut : Ingredients() object Sugar : Ingredients() private fun convertFlavorToString(ing: Ingridient): String { return when (ing) { is Chocolate -> "Chocolate" is Coconut -> "Coconut" is Sugar -> "Sugar" } }
  • 53. KOTLIN - DSL SEALED CLASSES - SMART CASTING sealed class VehicleState object Empty : VehicleState() data class Success(val vehicles: List<Vehile>) : VehicleState() data class Error(error: Throwable) : VehicleState() data class Loading(isLoading: Boolean) : VehicleState()
  • 54. KOTLIN - DSL SEALED CLASSES - SMART CASTING sealed class VehicleState object Empty : VehicleState() data class Success(val vehicles: List<Vehile>) : VehicleState() data class Error(error: Throwable) : VehicleState() data class Loading(isLoading: Boolean) : VehicleState() private fun updateState(state: VehicleState) { when (state) { is Empty -> ... is Success -> state.vehicles is Error -> state.error is Loading -> state.isLoading } }
  • 56. KOTLIN - DSL CAKE val cake = Cooker make Cake of Chocolate and Coconut withOut Sugar forMy Birthday print(cake)
  • 58. KOTLIN - DSL UNIT TEST data class User(val name:String, var balance: Double) { fun withDraw(value: Double){ this.balance -= value } }
  • 59. KOTLIN - DSL UNIT TEST //Given val user = User("Roque", 200.0) //When user.withDraw(50.0) //Then Truth.assertThat(user.balance).isEqualTo(150.0)
  • 60. KOTLIN - DSL UNIT TEST given { User("Roque", 200.0) }.test { withDraw(50.0) }.assert { Truth.assertThat(balance).isEqualTo(150.0) }
  • 61. KOTLIN - DSL UNIT TEST fun <T, R> T.given(block: () -> R): R { return block(this) }
  • 62. KOTLIN - DSL UNIT TEST fun <T> T.test(block: T.() -> Unit): T { block() return this }
  • 63. KOTLIN - DSL UNIT TEST fun <T> T.assert(block: T.() -> Unit) { this.block() }
  • 64. KOTLIN - DSL UNIT TEST given { User("Roque", 200.0) }.test { withDraw(50.0) }.assert { balance isEquals 150.0 }
  • 65. KOTLIN - DSL UNIT TEST infix fun<T> T.isEquals(value: T):{ Truth.assertThat(this).isEqualTo(value) }
  • 66. KOTLIN - DSL UNIT TEST whenever(repository.increase()).thenReturn(Counter(1))
  • 67. KOTLIN - DSL UNIT TEST whenever(repository.increase()).thenReturn(Counter(1)) repository.increase() willReturn Counter(1)
  • 68. KOTLIN - DSL UNIT TEST whenever(repository.increase()).thenReturn(Counter(1)) repository.increase() willReturn Counter(1) infix fun <T> T.willReturn(value: T) { given(this) .willReturn(value) }
  • 70. KOTLIN - DSL NEXT STEPS ▸Find your necessity ▸Check if already exist ▸Sync with your team ▸Be creative ▸Enjoy more readable code :)
  • 71. KOTLIN - DSL SUMMARIZE ▸Infix notation ▸Sealed Class ▸Higher order functions ▸Lambda with receivers ▸Lambda parameter ▸Operator overloading

Editor's Notes

  • #4: You will see a lot of code, if you are not that familiar with kotlin it might be like What is this, but I’m pretty sure you will learn something in general about DSL and be able to apply in your language/project.
  • #5: Content 2018 but there are still a lot of things to learn
  • #6: DSL is not only one feature from kotlin It’s actually not even a kotlin feature DSLs are languages which belongs for specific domains Bring to kotlin and the fancy way as possible
  • #7: Why should I know about DSL if I’m not using SQL or HTML or any other domain specific language in my code?
  • #8: Even kotlin is creating dsl from kotlin to kotlin Introduced in kotlin 1.3 Composable code Structure Functional programming Declarative Build list return list directly Huge reason to create DSL already
  • #10: Could be a date class but for the example fit better being just a class
  • #11: Java Not very kotlin What is the problem of this code? No context I can change the fields from anywhere Scope function
  • #12: Not when/where to use But how it works Dive deep into ti and see What scope function can TEACH us about high order functions.
  • #13: Lambda context High order function
  • #14: Omit my this Same that omit this activity
  • #15: If I print hellowWorld valuable, what will be the output of this? Kudos for who said Hello Do you know why do we have this output? Not concating? Not returning the last line? Why I have this inside the block? Lot of questions, right? Let’s dive deep to apply function and find more about it.
  • #16: Generic Extension function for any type High order function, receiving other function Adding my T as lambda receiver my context of my lambda Return the same type
  • #18: What will be the output of this?
  • #20: High order function
  • #21: High order function with lambda parameter
  • #22: High order function with lambda receiver and lambda parameter
  • #23: Extension function High order function With lambda receiver Without return
  • #24: 15 min Extension function High order function With lambda receiver With return
  • #27: Now the lib code seems not that weird for us High order function and receivers
  • #29: No structure, have type
  • #30: Bringing sql to kotlin domain Lib abstract Create my own, very poor but just to show two kotlin features.
  • #31: This will result in my sql string.
  • #33: If you follow you can use it
  • #34: Fake constructor initialising my query Infix Lambda receiver
  • #35: Could be better, but it’s just to show the infix and the operator overloading features
  • #36: User object What is select? Infix hight order function that contain lambda with receiver which is my user. Operator overloading to create fake constructor User to start my query Age concate my query and return my user Eq infix function contain int parameter and print my query
  • #37: 25 min Output
  • #38: Favorite Write in English
  • #39: Is possible to have chocolate without sugar? Not sure Is possible to write English with kotlin? YES
  • #41: Not English yet
  • #42: Not close yet
  • #43: Almost there If I make my cake object then it’s done Dish parameter
  • #45: You can’t extend in other file
  • #51: Show the parent
  • #53: Remove the braces
  • #55: Not SN code
  • #56: Access to the fields
  • #57: Only two features helped me to create my cake DSL
  • #58: 32 min And write in English inside kotlin domain
  • #59: Cake was funny but yeah, not very useful Readability
  • #60: Test withDraw
  • #61: The standard
  • #62: Structure
  • #63: Extension function High order function Return last line
  • #64: Extension function High order function Return same type
  • #65: Extension function High order function Without return
  • #66: What about I could extract the truth lib?
  • #67: If I want to change my assert library, I have only few places and not in all my unit tests
  • #68: Verbose
  • #69: Readability
  • #70: Method call will return
  • #71: 40min How create is done When to create a DSL? Easy WillThrow or others Be creative