-
-
Save bkahlert/5c66192b5a06de16420471de723deade to your computer and use it in GitHub Desktop.
Multiple receivers in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can actually get rid of one explicit parameter by defining:
and