Kotlin: const val vs val

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" // declared in the same file. class MyFragment { ... } 

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.

+5
source share
3 answers

Each time you write a (non-built-in) lambda expression, you create a different class. Compared to this, creating one class to hold top-level ads seems insignificant.

In addition, if everything you have at the top level is a constant declaration, it will be included in each site used (according to the specification), so the owner class itself will become unaccounted for and, therefore, aims to minimize ProGuard. It most likely will not appear in your production APK.

+6
source

There is not only a semantic difference between the two parameters.

Option 1 ( val inside the class) is an instance field.

Option 2 (the upper level is const val ) is a "static" member of the upper level (something like this since static does not exist in Kotlin.)

That's why you created the MyFragmentKt class: top-level members are compiled into the class name [Filename]Kt .

I would consider the third option:

 class MyFragment { companion object { private const val MY_KEY = "my_key" } } 

Thus, MY_KEY is (from Java) a member of the static class MyFragment , since JvmStatic is output for const variables. The Companion class will be created (but it will be empty).

Since your original approach was a field inside the class, it seems to me that the constant companion object / static might be preferable.

More on companion object vs Java static

+3
source

I think option number 2 is the right way.

-1
source

Source: https://habr.com/ru/post/1275209/


All Articles