Search code examples
javaandroidkotlinconstants

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


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?


Solution

  • 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