liveBook · Manning

Context receiver

As explained in Kotlin in Action, 2E

A context receiver is a Kotlin language feature that lets a function declare an additional required receiver type.

A context receiver lets a Kotlin function require an additional receiver type. It addresses a limitation of member extension functions: useful extensions may need several receivers without modifying the original class. section 13.4.3

Adding a table context

context(Table) fun Column<Int>.autoIncrement(): Column<Int> { // access properties and methods of both Table and Column<Int> } The function extends Column<Int>, while context(Table) supplies the additional Table receiver needed by its implementation. section 13.4.3

This pattern suits internal DSLs such as database table definitions. The autoIncrement call can remain an extension on Column<Int> while also accessing its surrounding Table context. section 13.4.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines the syntax and motivation with an Exposed example, but stops short of finalized language specification details.
Examples
Uses Exposed's autoIncrement extension, Table and Column<Int> receivers, and database column declarations.
What it assumes
Assumes familiarity with Kotlin extension functions and member extension functions, while motivating why one receiver can be insufficient.
What you can do after
Evaluate and apply the prototype syntax for extensions requiring both a surrounding Table and a Column<Int> receiver.
How it connects
Connects context receivers with member extension functions, extension functions, and internal DSL construction.

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.