https://kotlinlang.org logo
Title
e

eekboom

04/10/2023, 2:39 PM
👋 How do I get the java class name of a Kotlin file that contains no classes? (I have Ktor Routing extension functions in a file and want to configure a logger with a Java class name, so that I don't have to manually code the logger name (and don't forget to update it when I rename the file.) For example, I see that for a file RegisterRouting.kt Kotlin created a class named RegisterRoutingKt, but is there a function to get that name?
c

Chris Lee

04/10/2023, 2:45 PM
kotlin-logging may help with this.
a

Adam S

04/10/2023, 2:50 PM
I’ve seen this hack before
fun main() {
  println(object {}.javaClass.name)
}
e

eekboom

04/10/2023, 2:50 PM
Ha, thanks Adam! I had cloned kotlin-logging and just this moment, found that it uses exactly this 😄
a

Adam S

04/10/2023, 2:51 PM
ah no, this is it https://stackoverflow.com/a/45782816/4161471
fun main() {
  println(object{}.javaClass.enclosingClass)
}
kotlin-logging is a good shout 👍
btw “Kotlin file that contains no classes”, the official term is ‘top level function’ or ‘top level declaration’. That might help with searches in the future :)
e

eekboom

04/10/2023, 2:56 PM
Thanks! Indeed, I already searched on SO without success and of couse, it doesn't really matter if the Kotlin files contains classes as well.