liveBook · Manning

This expression

As explained in Kotlin in Action, 2E

A labeled this expression is a Kotlin expression that refers to the receiver associated with a specified label.

A labeled this expression selects a particular receiver when nested Kotlin scopes provide more than one implicit this reference. In a String extension using buildString, this@filter refers to the input String while this refers to the StringBuilder. section 10.1.2

Selecting the outer receiver

fun String.filter(predicate: (Char) -> Boolean): String { return buildString { for (char in this@filter) { if (predicate(char)) append(char) } } } Here, this@filter iterates over the receiver String, while buildString supplies the inner StringBuilder receiver. Calling "ab1c".filter { it in 'a'..'z' } produces abc. section 10.1.2

fun main() {
    println(StringBuilder().apply sb@{         #1
       listOf(1, 2, 3).apply {                 #2
           this@sb.append(this.toString())     #3
       }
    })
    // [1, 2, 3]
}

Nested apply blocks demonstrate explicit receiver labeling: this@sb reaches the outer StringBuilder, while this refers to the inner receiver. section 10.3.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains explicit labels, function-name labels, and receiver selection in nested lambdas without descending into compiler internals.
Examples
Uses a String.filter implementation and nested StringBuilder.apply blocks to show outer and inner receiver access.
What it assumes
Assumes familiarity with Kotlin lambdas, extension functions, implicit receivers, and higher-order functions.
What you can do after
Apply labeled receiver access to write and read nested Kotlin lambdas without selecting the wrong implicit receiver.
How it connects
Connects labeled this expressions with lambdas with receivers, extension functions, higher-order functions, and lambda labels.

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.