I\'m creating my first Kotlin classes in my Android application. Usually for logging purposes I have a constant with name TAG
. What I would do in Java is:
I found a way which is more "copy-paste"-able, since it doesn't require you to type the name of your class:
package com.stackoverflow.mypackage
class MyClass
{
companion object {
val TAG = this::class.toString().split(".").last().dropLast(10)
}
}
It's not the most elegant solution but it works.
this::class.toString().split(".").last()
will give you "com.stackoverflow.mypackage.MyClass$Companion"
so you need the dropLast(10)
to remove $Companion
.
Alternatively you can do this:
package com.stackoverflow.mypackage
class MyClass
{
val TAG = this::class.simpleName
}
But then the TAG
member variable is no longer "static" and doesn't follow the recommended naming conventions.