Not wanting to resurrect a 6-year old topic I have a similar requirement but not just for logging. Has the ability to retrieve the packageName at the top-level in a file been added since then? I haven’t been able to find anything.
Given my more varied requirements the most succinct thing I could come up with was this (keeping it in the ‘logger’ vein for this example):
private val packageName: String = (object {}).javaClass.packageName
private val logger = LoggerFactory.getLogger(packageName)
This still feels somewhat contorted to get what should be a readily available attribute.
You have to do that though. The point of the inline function here is to create a new anonymous class where it’s called, so that the class has that package. What you can do is have a private val packageName = packageName() at the file level
Thanks @kyay10 for the inline fun. I was close on that but didn’t quite get there. And yes, I’d replace the existing code to set the val because the value is used in a lot of places so the object creation would need to be minimized.
Hopefully we’ll see a language/lib-provided mechanism in the (near?) future.
inline fun packageName(noinline block: () -> Unit): String = block.javaClass.packageName
val pkg = packageName{}
It doesn’t allocate anything per use and should be generally quick enough to be used directly in the code, but a huge drawback is its non-standard calling style. Implementation can’t be easily replaced in the future if needed. Also, it creates a separate class and its instance per each call-site.