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

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

    In Android Studio, the usual way to rename something is to right-click the name, select Refactor->Rename. So, I think it's fine to do something like this,

    class MyClass {
        companion object {
            private const LOG_TAG = "MyClass"
        }
    }
    

    because if you rename the class MyClass like I described, then the IDE will suggest renaming your LOG_TAG String as well.

    Ultimately there are pros and cons of using this method vs. other methods. Because LOG_TAG is a String, there's no need to import the kotlin-reflect.jar, as you would if you set LOG_TAG equal to MyClass::class.simpleName. Also because the variable is declared as a compile-time constant with the const keyword, the generated bytecode is smaller since it doesn't need to generate more hidden getters, as described in this article.

提交回复
热议问题