Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple receivers in Kotlin
fun <A, B, C, R> multiReceiver(f: A.() -> B.() -> C.() -> R) = { a: A, b: B, c: C -> f(a)(b)(c) }
val sample1: (X, Y, Z) -> Int = multiReceiver { { { x + y + z } } }
val sample2: X.() -> Y.() -> Z.() -> Int = { { { x + y + z } } }
class X(val x: Int)
class Y(val y: Int)
class Z(val z: Int)
fun main() {
val result1 = sample1(X(1), Y(2), Z(3))
val result2a = sample2(X(1))(Y(2))(Z(3))
val result2b =
with(X(1)) {
with(Y(2)) {
with(Z(3)) {
sample2()()()
}
}
}
println(result1) // = 6
println(result2a) // = 6
println(result2b) // = 6
}
@bkahlert

This comment has been minimized.

Copy link
Owner Author

@bkahlert bkahlert commented Feb 25, 2021

You can actually get rid of one explicit parameter by defining:

val X.sample3: Y.() -> Z.() -> Int get() = { { x + y + z } }

and

val result3 =
        with(X(1)) {
            with(Y(2)) {
                with(Z(3)) {
                    sample3()()
                }
            }
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment