-
Notifications
You must be signed in to change notification settings - Fork 0
/
22-dsls.kt
81 lines (60 loc) · 1.72 KB
/
22-dsls.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package org.athenian
import java.text.SimpleDateFormat
import java.util.*
// See:
// https://www.grokkingandroid.com/creating-kotlin-dsls/
// https://www.kotlindevelopment.com/kotlin-dsl/
// https://proandroiddev.com/writing-dsls-in-kotlin-part-2-cd9dcd0c4715
fun main() {
fun familyExample() {
class Family {
val members = mutableListOf<String>()
fun addMember(name: String) {
members += name
}
operator fun invoke(body: Family.() -> Unit) {
body()
}
}
val family = Family()
family {
addMember("Mom")
addMember("Dad")
addMember("Kid")
}
}
data class Address(val street: String, val number: Int, val city: String)
data class Person(val name: String, val dateOfBirth: Date, var address: Address?)
fun buildExample(): Person {
class AddressBuilder {
var street: String = ""
var number: Int = 0
var city: String = ""
fun build() = Address(street, number, city)
}
class PersonBuilder {
var name: String = ""
private var dob: Date = Date()
private var address: Address? = null
var dateOfBirth: String = ""
set(value) {
dob = SimpleDateFormat("yyyy-MM-dd").parse(value)
}
fun address(block: AddressBuilder.() -> Unit) {
address = AddressBuilder().apply(block).build()
}
fun build() = Person(name, dob, address)
}
fun person(block: PersonBuilder.() -> Unit): Person = PersonBuilder().apply(block).build()
return person {
name = "John"
dateOfBirth = "1980-12-01"
address {
street = "Main Street"
number = 12
city = "London"
}
}
}
println("Build example: ${buildExample()}")
}