I understand that in Kotlin, const val used to declare constants, and val is used for readonly properties. However, I am interested in the following case, which is more suitable for use.
Suppose I have a fragment that needs a key for saveInstanceState and restoreInstanceState . I am wondering which of the following two options is better:
Option 1:
class MyFragment { private val MY_KEY = "my_key" ... }
Option 2:
private const val MY_KEY = "my_key"
I would prefer #option 2, as it is clear that MY_KEY is a constant, and the value is determined at compile time. However, since it is declared at the top level, it is worth the class ie MyFragmentKt (suppose the file name is MyFragment.kt ) is created in the compiled java code. In #ption 1, no additional class is generated, and although the MY_KEY value will be assigned at runtime rather than constant, it has nothing to do with how it is used in this particular case.
So, although I personally prefer #ption 2, my analysis makes me think that #option 1 is no worse, if not better. I'm just wondering how other developers think about it, and if there are other advantages of #option 2 that I haven't thought about. Thanks.
source share