Reputation: 84
I would like in my Kotlin Android app to have singleton object with some static definitions of it's inner states.
As I understand, object
in Kotlin is for singleton, so I am trying this kind of approach:
object MySingleton
{
public const val _DEF_DEFINITION_NO_ONE: Byte = 1;
public const val _DEF_DEFINITION_NO_TWO: Byte = 2;
(...)
}
This is fine, but the problem is, to being able use these definitions, now I must create Object's instance first.
Just wondering if I am able in Kotlin to create this kind of construction and have access to these definitions without creating MySingleton
instance? Answer would be companion object
working similar as static
in other languages, but it's not allowed inside objects, only inside of classes.
Of course I can leave this as is or make these definitions global, but would like to know is it possible to do in a way I described? Or maybe should I design this in another yet way?
Upvotes: 3
Views: 2245
Reputation: 29844
There are two ways to work with static data in Kotlin:
An object
object ASingleton {
val CONSTANT_PROPERTY: Int = 1;
}
If you need a single instance class, which has only one state for each property, use a singleton. Note: There can only be one instance of this class and it is created for you by the compiler.
A class with a companion object
class ClassWithCompanionObject{
val someProperty: Int = 0; // instance bound
companion object {
val CONSTANT_PROPERTY: Int = 1;
}
}
If you need some static properties, and the rest should have a state which is bound to a certain instance, go with the class with companion object
.
Usage:
println(ASingleton.CONSTANT_PROPERTY)
println(ClassWithCompanionObject.CONSTANT_PROPERTY)
Upvotes: 6
Reputation: 81899
As you said, MySingleton
is an object
and thus a singleton. There's no need to create an instance of it (not even possible). You simply access it's constants in a static way like this: MySingleton._DEF_DEFINITION_NO_ONE
.
If you want to use the constants without prefixing the object
name, just import them with the fully-qualified name and use it as follows:
import package.MySingleton._DEF_DEFINITION_NO_ONE
//...
println(_DEF_DEFINITION_NO_ONE)
Upvotes: 4