[英]Kotlin - any substitute for companion object inside of another object (not class)?
I would like in my Kotlin Android app to have singleton object with some static definitions of it's inner states. 我希望在我的Kotlin Android应用程序中具有具有其内部状态的静态定义的单例对象。
As I understand, object
in Kotlin is for singleton, so I am trying this kind of approach: 据我了解,Kotlin中的
object
用于单例,因此我正在尝试这种方法:
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. 很好,但是问题是,要能够使用这些定义,现在我必须首先创建Object的实例。
Just wondering if I am able in Kotlin to create this kind of construction and have access to these definitions without creating MySingleton
instance? 只是想知道我是否能够在Kotlin中创建这种构造并无需创建
MySingleton
实例即可访问这些定义? Answer would be companion object
working similar as static
in other languages, but it's not allowed inside objects, only inside of classes. 答案将是
companion object
工作方式与其他语言中的static
companion object
类似,但不允许在对象内部,而只能在类内部。
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?
还是应该以其他方式设计这个?
As you said, MySingleton
is an object
and thus a singleton . 如您所说,
MySingleton
是一个object
,因此是一个单例 。 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
. 您可以像这样通过静态方式简单地访问其常量:
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: 如果要使用常量而不加
object
名称前缀,则只需使用完全限定的名称导入它们,并按如下所示使用它:
import package.MySingleton._DEF_DEFINITION_NO_ONE
//...
println(_DEF_DEFINITION_NO_ONE)
There are two ways to work with static data in Kotlin: 在Kotlin中有两种使用静态数据的方法:
An object
一个
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
具有
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
. 如果您需要一些静态属性,而其余的属性应具有绑定到特定实例的状态,请使用带有
companion object
的类。
Usage: 用法:
println(ASingleton.CONSTANT_PROPERTY)
println(ClassWithCompanionObject.CONSTANT_PROPERTY)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.