What is the best way to define log TAG constant in Kotlin?

I Like TAG to be an extension function as suggested by Fredy Mederos.

extending his answer to support anonymous classes :

 /**
 * extension function to provide TAG value
 */
val Any.TAG: String
    get() {
        return if (!javaClass.isAnonymousClass) {
            val name = javaClass.simpleName
            if (name.length <= 23) name else name.substring(0, 23)// first 23 chars
        } else {
            val name = javaClass.name
            if (name.length <= 23) name else name.substring(name.length - 23, name.length)// last 23 chars
        }
    }

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.

The best way (IMHO)

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")
    }
}

Another option

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")
    }
}

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