Reputation: 476
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:
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
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
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