Last active
February 7, 2018 09:31
-
-
Save noncom/ea3e57e676a799efe2943a34b06f2986 to your computer and use it in GitHub Desktop.
Kotlin extension function receiver type inference
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 Int.one(x: Int) = this + 1 + x | |
fun Int.two(x: Int) = this + 2 + x | |
fun Int.three(x: Int) = this + 3 + x | |
fun Int.noop(x: Int) = this + x | |
class Z(val action: Int.() -> Int) | |
object Test { | |
/** OK */ | |
fun test() { | |
val z = Z({one(1)}) | |
} | |
/** OK */ | |
fun test2() { | |
val f: Int.() -> Int = {one(10)} | |
val z = Z(f) | |
} | |
/** Does not compile! */ | |
fun test3() { | |
val choice = Random().nextInt(3) | |
// the receiver type does not get inferred with or without the explicit type annotation for `f` | |
val f: Int.() -> Int = when(choice) { | |
0 -> {one(10)} | |
1 -> {two(20)} | |
2 -> {three(30)} | |
else -> {noop(9000)} | |
} | |
val z = Z(f) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment