Why I can't access a method whose receiver is Test...
# getting-started
a
Why I can't access a method whose receiver is Test inside the class Test2 when inside a builder with Test ? But I can adding
with
of my instance of Test2.
Copy code
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 ?
    }
}
c
I think its because
with
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
Test
you can do the same with apply
where in the builder's context you only have scope of the
this
of
Test
which has no definition of
method
l
Your definition of
method
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:

https://www.youtube.com/watch?v=GISPalIVdQYâ–¾

a
Thanks, I didn't think about using context receivers 🙂