如何使用点表示法在类中更改变量?

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月23日 20:26:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定