Search code examples
kotlinkotlin-extension

How to access extension property inside object from outside class?


Example:

class Foo {
    fun foo() = Unit
}

object Bar {
    val Foo.foo get() = Unit
}

fun Foo.bar() = Bar.foo

Extension symbols aren't static when inside a class instance, so I don't see why this wouldn't be possible by simply passing in the receiver.


Solution

  • You can do this, but you have to bring the Bar into the context as a receiver as well, along with reference to someFoo.foo otherwise you are saying Bar has a property foo which it does not. It has within its scope (and its instance) the extension of Foo.foo. Therefore change your last line from:

    fun Foo.bar() = Bar.foo
    

    to:

    fun Foo.bar() = with (Bar) { foo }
    

    which is conceptually this:

    fun Foo.bar() = with (Bar) { this@bar.foo }
    

    So we use with to stack the Bar receiver under the Foo instance receiver of this@bar and access the property foo.