I understand in Kotlin const val
is used to declare constants and val
is for readonly properties. However, I'm wondering in the following case, which one is more suitable to use.
Assume I have a fragment which needs a key to use for saveInstanceState
and restoreInstanceState
. I'm wondering which one of the following 2 options is better:
Option 1:
class MyFragment {
private val MY_KEY = "my_key"
...
}
Option 2:
private const val MY_KEY = "my_key" // declared in the same file.
class MyFragment {
...
}
I'd prefer the #option 2 since it makes it clear that MY_KEY
is a constant and the value is determined in compile time. However since it's declared on the top level, it costs a class i.e. MyFragmentKt
(assume the file name is MyFragment.kt
) to be created in the compiled java code. In #option 1, no extra class is generated and although MY_KEY
's value is going to be assigned at runtime and not constant, that makes no difference in how it's used in this specific case.
So although I personally prefer #option 2, my analysis makes me think #option 1 is not worse, if not better. I'm just wondering how other developers think about this and if there are any other benefits of #option 2 that I haven't thought of. Thanks.