Skip to content

Instantly share code, notes, and snippets.

@lemnik
Created October 11, 2018 07:32
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 lemnik/928c8c8439dd83204007a11dc6eebeb8 to your computer and use it in GitHub Desktop.
Save lemnik/928c8c8439dd83204007a11dc6eebeb8 to your computer and use it in GitHub Desktop.
Using instance-function references in Kotlin
// 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