Created
October 11, 2018 07:32
-
-
Save lemnik/928c8c8439dd83204007a11dc6eebeb8 to your computer and use it in GitHub Desktop.
Using instance-function references 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
// https://pl.kotl.in/rJgInO29m | |
class MyClass { | |
private fun doThing1(name: String) = | |
println("Thing1 says: Hello $name") | |
private fun doThing2(name: String) = | |
println("Thing2 says: Hi $name!") | |
private fun fail(name: String) = | |
println("oops $name") | |
fun doThing(num: Int, name: String) { | |
// note the type-annotation with the reciever (type-annotation is only here for clarity) | |
val function: MyClass.(String) -> Unit = | |
when(num) { | |
1 -> ::doThing1 | |
2 -> ::doThing2 | |
else -> ::fail | |
} | |
// and now we can invoke it here, with many-many arguments if required | |
this.function(name) | |
} | |
} | |
fun main(args: Array<String>) { | |
val wrapper = MyClass() | |
wrapper.doThing(1, "Sally") | |
wrapper.doThing(2, "Conrad") | |
wrapper.doThing(3, "Cat") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment