Extension function with receiver inside Object-declaration

I have a state singleton and want to delegate some values of other classes to it.

This works:

data class MyState(val something: String) {}

object Singleton {
    var currentState = MyState("hi")
}

fun <T> stateFn(stateFn: (MyState) -> T): Lazy<T> {
    return lazy { stateFn(Singleton.currentState) }
}

class X {
    val hi: String by stateFn { s -> s.something }
}

But I would like to make currentState private in my singleton and move the stateFn into the object like this:

object StateHolder {
    private var currentState = MyState("hi")

    fun <T> stateFn(stateFn: (MyState) -> T): Lazy<T> {
        return lazy { stateFn(this.currentState) }
    }
}

If I do that I have to qualify my delegate with the object.

class X {
    val hi: String by StateHolder.stateFn { s -> s.something }
}

Is there a way around this?

If you want to write only by stateFn instead of by StateHolder.stateFn, you could import the function:

import your.package.StateHolder.stateFn

Great, thanks. I tried this out earlier and for some reason it didn’t work then…