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

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

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

提交回复
热议问题