Kotlin equivalent of Swift's struct?


#1

In Swift, I like to use structs to store a bunch of constants like a certain integer or color I would like to use throughout the app. Some of these have to be determined at runtime. What would be the Kotlin equivalent of this?

Do I have to create a data class with a dummy parameter with a default value, and store the constants in that class?

Do I have to create a normal class with a companion object and store constants in there? If so, how does that affect performance? Does it still instantiate the class if I use it many times?

What if I create a class with no companion object, but several other objects stored in it instead, each with their own set of constants. How does this affect performance?

Do I create an object and store constants in there? Is it automatically a singleton object?

Or is there a better way to go about this?


#2

I think you are looking for an object declaration which is in essence a Singleton.

Though I wouldn’t compare it to a struct since that has a different meaning and behaviour in most other languages.


#3

Thanks for your help! I was looking for a way to determine constants at runtime, to then use them throughout the app. I believe an object declaration will do the trick for me. Thank you!


#4

And realize that you don’t have to put those constants in anything. They can be at the top level in Kotlin.


#5

Thanks for the tip!