Ayfri
11/18/2022, 11:06 PMwith of my instance of Test2.
class Test(var name: String = "test")
class Test2 {
fun Test.method() = name
}
fun builder(block: Test.() -> Unit) = Test().apply(block)
fun main() {
val a = Test2()
builder {
with(a) {
println(method()) // can access method()
}
println(a.method()) // cannot access a.method() for some reason ?
}
}Cody Mikol
11/19/2022, 12:54 AMwith is making the context of its lambda the this of a / Test2 which has an extension function with the ability to alter the context of the outer builder's this of class TestCody Mikol
11/19/2022, 12:55 AMCody Mikol
11/19/2022, 12:55 AMthis of Test which has no definition of methodLoney Chou
11/19/2022, 3:44 AMmethod implies that it's only callable (or to say "dottable") on Test but not Test2. a.method means you're calling method on Test2. This is where context receiver differs from common receiver. If you have context(Test) fun method() instead then you can a.method because Test is already in the context (from builder lambda). If you don't know what context receiver is, check this video: Ayfri
11/19/2022, 4:54 AM