-
Notifications
You must be signed in to change notification settings - Fork 0
/
13-lambdas-with-receiver.kt
66 lines (49 loc) · 1.36 KB
/
13-lambdas-with-receiver.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
package org.athenian
// See: https://proandroiddev.com/writing-dsls-in-kotlin-part-1-7f5d2193f277
fun main() {
data class Address(var street: String? = null, var city: String? = null)
data class Person(var name: String? = null, var age: Int? = null, var address: Address? = null)
fun lambdaArg(): Person {
// Lambda arg
fun person(block: (Person) -> Unit): Person {
val p = Person()
block(p)
//block.invoke(p)
return p
}
return person { p: Person ->
p.name = "John"
p.age = 25
}
}
fun lambdaWithReceiverArg(): Person {
// Lambda with receiver arg
fun person(block: Person.() -> Unit): Person {
val p = Person()
p.block()
//p.apply(block)
return p
}
return person {
this.name = "Mary"
this.age = 26
}
}
fun embeddedLambdaWithReceiverArg(): Person {
fun person(block: Person.() -> Unit): Person = Person().apply(block)
fun Person.address(block: Address.() -> Unit) {
address = Address().apply(block)
}
return person {
name = "Tracey"
age = 21
address {
street = "123 Main"
city = "Houston"
}
}
}
println("Lambda Arg: ${lambdaArg()}")
println("Lambda With Receiver Arg: ${lambdaWithReceiverArg()}")
println("Embedded Lambda With Receiver Arg: ${embeddedLambdaWithReceiverArg()}")
}