class Person(val name: String) {
fun sayHello() = println("Hello!")
}
class Dog(val name: String) {
fun bark() = println("Ruff!")
}
val person = Person("Julia")
val dog = Dog("Sparky")
with(person) {
with(dog) {
println(name) // Prints Sparky from the dog object
bark() // Calls bark() on the dog object
sayHello() // Calls sayHello() on the person object
}
}
with(person) {
with(dog) {
println(this.name) // Prints Sparky
this.bark() // Calls bark() on the dog object
this.sayHello() // Compiler error - Unresolved reference: sayHello
}
}
When using this, it will only refer to the exact implicit receiver in that scope.
When omittingthis, the effective receiver is a combination of the implicit receivers, from the innermost to the outermost scope.