英文:
Singleton in Kotlin
问题
I want to implement "singleton" pattern in Kotlin. I wrote something like this.
class MySingleton {
companion object {
val instance = MySingleton
}
}
But now users can create instances.
val mySingleton = MySingleton()
I want allow only this way.
val instance = MySingleton.instance
How can I ban using a constructor of my class?
英文:
I want to implement "singleton" pattern in Kotlin. I wrote something like this.
class MySingleton {
companion object {
val instance = MySingleton
}
}
But now users can create instances.
val mySingleton = MySingleton()
I want allow only this way.
val instance = MySingleton.instance
How can I ban using a constructor of my class?
答案1
得分: 3
如果您使用对象而不是类,您可能会有更好的运气。
即。
object MySingleton {
val thingA = 0
}
英文:
if you use an object instead of a class you may have better luck
ie.
object MySingleton {
val thingA = 0
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论