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:
Declare of TAG variable with val
class YourClass {
companion object {
//if use java and kotlin both in project
//private val TAG = MyClass::class.java.simpleName
//if use only kotlin in project
private val TAG = YourClass::class.simpleName
}
}
Use the variable like
Log.d(YourClass.TAG, "Your message");
//or
Log.e(TAG, "Your message");
You can try this:
companion object {
val TAG = ClearCacheTask::class.java.simpleName as String
}
This extension allows us to use TAG in any class
val Any.TAG: String
get() {
val tag = javaClass.simpleName
return if (tag.length <= 23) tag else tag.substring(0, 23)
}
//usage
Log.e(TAG,"some value")
It it also validated to work as an Android valid Log tag.
The best way to log (imho) is using Timber: https://github.com/JakeWharton/timber
But if you don't want to use library then
TAG can be defined as an inlined extension property (e.g. in Extensions.kt
):
inline val <reified T> T.TAG: String
get() = T::class.java.simpleName
Some more extensions to not to write TAG all the time in Log.d(TAG, "")
:
inline fun <reified T> T.logv(message: String) = Log.v(TAG, message)
inline fun <reified T> T.logi(message: String) = Log.i(TAG, message)
inline fun <reified T> T.logw(message: String) = Log.w(TAG, message)
inline fun <reified T> T.logd(message: String) = Log.d(TAG, message)
inline fun <reified T> T.loge(message: String) = Log.e(TAG, message)
And then you can use them in any class:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
logd("Activity created")
}
You can define your TAG
by @JvmField
as below:
companion object {
@JvmField val TAG: String = MyClass::class.java.simpleName
}
For more details, you can read this article : Kotlin's hidden costs
Updated answer with Kotlin 1.2.20
class MyClass {
companion object {
@JvmField
public val FOO = 1
}
}
uses
MyClass.FOO