https://kotlinlang.org logo
t

taer

10/22/2020, 4:02 PM
Looking to make a delegate that returns the class name. Something like this:
Copy code
private val logger by OurLogger()
I have a delegate working perfectly for class properties.
Copy code
class OurLogger {
    operator fun provideDelegate(thisRef: Any, prop: KProperty<*>) = LoggingDelegate(thisRef.javaClass.name)
}
class LoggingDelegate(klassName: String) : ReadOnlyProperty<Any?, Logger> {
    private val capturedLogger = LogManager.getLogger(klassName)
    override fun getValue(thisRef: Any?, property: KProperty<*>): Logger = capturedLogger
}
I can't get it to work though for top level properties. It seems to be looking for a
provideDelegate(thisRef: Nothing?, prop: KProperty<*>
which makes sense because it doesn't have a this. In my case, using the generated class that houses the static variable(aka, the fileNameKT) would be fine, but I can't figure out how to get the
provideDelegate(thisRef: Any, prop: KProperty<*>)
vs
provideDelegate(thisRef: Nothing?, prop: KProperty<*>)
to work. The second I make the thisRef Nothing, I can't do anything w/ it. I looked at the implementation of
Lazy
it seems to get away with it on the top level via an extension function
kotlin.Lazy<T>.getValue(thisRef: kotlin.Any?, property: kotlin.reflect.KProperty<*>)
Any advice on the top-level stuff?
Or a better channel to ask in. 🙂
The extension function thing that Lazy did worked. I now get a proper
null
thisRef in my getValue. And advice now on the "how to get the synthetic class" that namespaces the top level?
I think it's this simple. Probably a better way, but looks ok for now
Copy code
val stackTrace = RuntimeException().stackTrace
            val x = if(stackTrace.size < 2){
                "unknown"
            }else{
                stackTrace[1].className.removeSuffix("Kt")
            }