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

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

    Here is my extension function in kotlin, just add it in your extensions file.

    val Any.TAG: String
    get() {
        return if (!javaClass.isAnonymousClass) {
            val name = javaClass.simpleName
            if (name.length <= 23 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) name else
                name.substring(0, 23)// first 23 chars
        } else {
            val name = javaClass.name
            if (name.length <= 23 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                name else name.substring(name.length - 23, name.length)// last 23 chars
        }
    }
    

    Then you can use TAG in any class like below:

    Log.d(TAG, "country list")
    

提交回复
热议问题