This Week I Learned: Kotlin receivers [2022–04–22]
Kotlin has this way of passing a function as an argument to a higher-order function that lets you write less code.
Take a look at this contrived example:
The fun part is inside exampleCaller
. See the bah()
? I didn’t have to write the argument list and specify what object is receiving the call. It’s a bit more succinct and looks neat.
Implicitly, there is a this
object inside the code block and its type is Foo
. The syntax that tells Kotlin this is the Foo.
in the Foo.() -> String
.
In this tiny example it doesn’t make very much difference, but it’s nice when there are a bunch of function calls and I’d have to repeat this.
a lot.
It can also help make code easier to read, I think. We can use this syntax to almost write sentences:
showMe {
aKotlinExample()
}