This Week I Learned: Kotlin receivers [2022–04–22]

Peter Brownlow
2 min readApr 22, 2022

--

Photo by dan carlson on Unsplash

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()
}

--

--

Peter Brownlow
Peter Brownlow

Written by Peter Brownlow

Software builder, people manager, topical deep-dive enthusiast

No responses yet