英文:
How to change a variable in a Class with dot notation?
问题
class MyClass(me: String) {
var name: String = "My Name"
}
为什么无法执行以下操作:
MyClass.name = "New Name"
我想要在主类中更改变量的值,而不想创建一个实例来执行此操作。在Kotlin中是否可能?
创建实例并更改该值显然不会更改主类的值,所以我主要寻找一种使用点符号来从主类中更改变量的方法,
这是否可能?
英文:
class MyClass(me : String) {
var name :String = "My Name"
}
Why can't i do
MyClass.name = "New Name"
I want to change the variable value in the main class, And i don't want to create an instance to do this. Is it possible in kotlin?
Creating instance and changing that value obviously doesn't change the value of main class, So i am mainly looking for a way to change the variable from the main class using the dot notation ,
Is it possible?
答案1
得分: 0
当然,要实现这个,只需将您的变量放入一个伴随对象,如下所示:
class MyClass(me: String) {
companion object {
var name = "我的名字"
}
}
在您当前的实现中,name
是一个实例属性,但显然您希望它是您的类的静态属性。
英文:
Sure, to accomplish this just put your variable into a companion object like this:
class MyClass(me : String) {
companion object {
var name = "My Name"
}
}
In your current implementation, name
is an instance property, but you clearly want it to be a static property of your class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论