Skip to content

Instantly share code, notes, and snippets.

@bkahlert
Forked from Takhion/MultiReceiver.kt
Last active February 25, 2021 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bkahlert/5c66192b5a06de16420471de723deade to your computer and use it in GitHub Desktop.
Save bkahlert/5c66192b5a06de16420471de723deade to your computer and use it in GitHub Desktop.
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
Copy link
Author

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