Ctorres
Ctorres

Reputation: 476

What's the proper way to create global constants in Kotlin?

I wonder what's the best way to create global constants in Kotlin. In Java, we would use a class with the constants inside, and we just have to import this class to access all the constants. But in Kotlin there's two main ways to do so:

  1. You can create an object which contains all your constants :

    object Constants { const val CONST_1 = "foo" const val CONST_2 = "bar" const val CONST_3 = "toto" }

But it's not the recommanded way, as one of the language developer said here : https://discuss.kotlinlang.org/t/best-practices-for-top-level-declarations/2198/3

  1. The second way is to use the top-level declaration, which is in my opinion not the best way to do because the more constants you have the more you IDE will be autocomplete your code with your constants names... And you have to import every constants one by one to use them.

I wonder so if there a better solution. I don't want to flood my IDE with hundreds of top-level declarations, tons of imports, but the "object" way is apparently not recommanded.

What should I do, then?

Thank you for helping

Upvotes: 2

Views: 1868

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17701

Second way is preferred, as yo yourself noted.

And you don't have to import constants one by one, as you can import the entire package containing them.

There's also no major problem with the first approach. Just try to avoid having those as companion objects.

Upvotes: 3

Related Questions