liveBook · Manning

Receiver

As explained in Kotlin in Action, 2E

A receiver is an entity that accepts a message or signal, or an object on which a method or command operates.

In Kotlin, a receiver is the value on which an extension function or receiver lambda operates. The receiver type names the type being extended; the receiver object is the instance supplied at the call site. section 3.3 section 13.2.1

An extension function receiver

fun String.lastChar(): Char = get(length - 1) println("Kotlin".lastChar()) // n String is the receiver type, and "Kotlin" is the receiver object. Inside lastChar, the receiver is available as this, although Kotlin normally lets you omit it. The function can use public members of String but cannot access private or protected members. section 3.3

Receiver syntax also supports configurable blocks:

  • A receiver lambda changes (StringBuilder) -> Unit into StringBuilder.() -> Unit. The supplied StringBuilder becomes the lambda's implicit this. section 13.2.1
  • Inside a receiver lambda, members can be called directly: append("World!") is shorthand for this.append("World!"). section 13.2.1
  • From Java, an extension function appears as a static method whose first argument is the receiver object, such as StringUtilKt.lastChar("Java"). section 3.3.2
package strings

fun String.lastChar(): Char = this.get(this.length - 1)

Inspect the compact declaration showing the receiver type before the extension function name and receiver members used in the body. section 3.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains receiver types, receiver objects, implicit this, lambda invocation, encapsulation limits, and Java compilation behavior.
Examples
Uses String.lastChar, buildString with StringBuilder, stored appendExcl, and a Java call to StringUtilKt.lastChar.
What you can do after
Apply Kotlin extension functions and receiver lambdas while translating their calls to Java static-method syntax.
How it connects
Connects receivers to extension functions, extension function types, lambdas with receivers, builder patterns, and Java interoperability.

Also explained in

Compare how 3 books explain receiver →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.