Question about generated code for private static final field in companion object


#1

I created a private static final field log in a class like this:

import org.slf4j.LoggerFactory

open class Person {

    companion object {
        private val log = LoggerFactory.getLogger(Person::class.java)
    }

    fun hello() {
        log.info("hello")
    }
}

I found out in the generated java code, the log in hello() method is accessed by calling the Companion.getLog():

   public final void hello() {
      Companion.getLog().info("hello");
   }

I wonder why the generated code is not log.info("hello") instead? Is there a way to force it to use direct field access instead?

Also what is the purpose of generated private final Logger getLog() method in the Companion class?


#2

The generated bytecode is indeed not optimal here, so I’ve reported an issue: https://youtrack.jetbrains.com/issue/KT-14258. Thanks!

One workaround that I can think of is to use the @JvmField annotation, however it’s not allowed on private properties, so log would have to be made non-private. I don’t recommend this though, as I think the VM must be perfectly capable of optimizing this access by itself, if it proves necessary.