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

后端 未结 17 2143
暗喜
暗喜 2021-01-30 16:00

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:



        
17条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 16:18

    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.

提交回复
热议问题