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:
private static final String TAG = MyClass.class.getSimpleName();
I know that in Kotlin classes I can create TAG
using this way:
private val TAG = MyClass::class.java.simpleName
This is OK for projects that use Java and Kotlin but what if I start a new project that is only in Kotlin? How can I define there TAG
constant? Is there more Kotlin way where I don't have this strange construction class.java.simpleName
?
To define a String constant in Kotlin, use constant and val keyword for the String. The following is a simple code snippet to define a String as constant which can be accessed using the name GREETING . const val GREETING = "Hello World!"
kotlin.Any. ↳ android.nfc.Tag. Represents an NFC tag that has been discovered. Tag is an immutable object that represents the state of a NFC tag at the time of discovery.
You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants. kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file.
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.
In general constants are all caps (ex. FOO) and located in the companion object:
class MyClass {
companion object {
public const val FOO = 1
}
}
and to define the TAG field you can use:
private val TAG = MyClass::class.qualifiedName
Commonly suggested approach of using the companion object
generates extra static final
instance of a companion class and thus is bad performance and memory-wise.
Define a log tag as a top-level constant, thus only extra class is generated (MyClassKt
), but compared to companion object
there will be no static final
instance of it (and no instance whatsoever):
private const val TAG = "MyLogTag"
class MyClass {
fun logMe() {
Log.w(TAG, "Message")
}
}
Use a normal val
. Though this looks unusual to see a log tag not as an all-uppercase constant, this will not generate any classes and has least overhead.
class MyClass {
private val tag = "myLogTag"
fun logMe() {
Log.w(tag, "Message")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With