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
