Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple receivers in Kotlin
val sample: (X, Y, Z) -> Int = multiReceiver { { { x + y + z } } }
fun <A, B, C, R> multiReceiver(f: A.() -> B.() -> C.() -> R) = { a: A, b: B, c: C -> f(a)(b)(c) }
class X(val x: Int)
class Y(val y: Int)
class Z(val z: Int)
@bkahlert

This comment has been minimized.

Copy link

@bkahlert bkahlert commented Feb 25, 2021

It would have saved me hours if someone told me, how to actually call sample now.
Answer is: sample(X(1), Y(2), Z(3))
I hope that helps future desperate souls looking for ways to accept multiple receivers.

Everyone trying to find out what sample would look like without the multiReceiver helper:

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

class X(val x: Int)
class Y(val y: Int)
class Z(val z: Int)

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