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

后端 未结 17 2101
暗喜
暗喜 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:21

    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");
    
    0 讨论(0)
  • 2021-01-30 16:21

    You can try this:

    companion object {
        val TAG = ClearCacheTask::class.java.simpleName as String
    }
    
    0 讨论(0)
  • 2021-01-30 16:22

    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.

    0 讨论(0)
  • 2021-01-30 16:23

    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")
    }
    
    0 讨论(0)
  • 2021-01-30 16:23

    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

    0 讨论(0)
  • 2021-01-30 16:27

    Updated answer with Kotlin 1.2.20

    class MyClass {
        companion object {
    
            @JvmField
            public val FOO = 1
        }
    }
    

    uses

    MyClass.FOO
    
    0 讨论(0)
提交回复
热议问题