How to use Function Literals with Receiver in Kotlin

Issue #139

From https://kotlinlang.org/docs/reference/lambdas.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class HTML {
fun body() { ... }
}

fun html(init: HTML.() -> Unit): HTML {
val html = HTML() // create the receiver object
html.init() // pass the receiver object to the lambda
return html
}


html { // lambda with receiver begins here
body() // calling a method on the receiver object
}

From https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/util/Standard.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}

val person = Person().apply {
name = "Superman"
age = 20
}

From https://academy.realm.io/posts/kau-jake-wharton-testing-robots/

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
fun payment(func: PaymentRobot.() -> Unit) = PaymentRobot().apply { func() }

class PaymentRobot {
fun amount(amount: Long) {

}

fun recipient(recipient: String) {

}

infix fun send(func: ResultRobot.() -> Unit): ResultRobot {
// ...
return ResultRobot().apply { func() }
}
}

class ResultRobot {
func isSuccess() {

}
}

payment {
amount(4200)
recipient(superman@google.com)
} send {
isSuccess()
}

Comments