Search code examples
kotlinextension-function

Can I use an extension *member* from outside the class?


If I have an extension function for type A declared inside class B:

class A

class B {
    fun A.foo() = "Hello"
}

Can I call this function at all from code that is outside class B?

val a = A()
val b = B()
a.foo()      // error: unresolved reference: foo
b.foo()      // error: unresolved reference: foo

Solution

  • Yes:

    with(b) { 
        a.foo() 
    } 
    

    Other functions accepting a lambda with a B receiver would work as well.