英文:
Kotlin: share variable in abstract class between extending classes
问题
我有一个抽象类A,类B和类C都是它的扩展类。
我希望在类A中有一个静态变量,我可以从类B和类C中获取和设置,以便它们可以访问共享值。
目前,使用getter和setter,类B和类C各自有其自己的变量实例。
老实说,我并不太关心是好的还是不好的做法,我只是想让它以某种方式工作。
英文:
I have an abstract class A of which the classes B and C are extending.
I want to have a static variable in class A that I can get and set from B and C so that they access a shared value.
Currently, using getters and setters B and C each have their own variable instance.
Honestly I don't care that much about good or bad practice, I just want to make it somehow work.
答案1
得分: 1
你可以使用companion object
来模拟静态变量:
abstract class A {
companion object {
var staticVariable: Int = 0
}
}
class B : A() {
fun updateStaticVariable() {
staticVariable = 1
}
}
class C : A() {
fun updateStaticVariable() {
staticVariable = 2
}
}
从其他位置访问它:
val sv = A.staticVariable
if (sv == 0) {
//...
}
英文:
You can use companion object
to simulate static variable:
abstract class A {
companion object {
var staticVariable: Int = 0
}
}
class B : A() {
fun updateStaticVariable() {
staticVariable = 1
}
}
class C : A() {
fun updateStaticVariable() {
staticVariable = 2
}
}
To access it from another place:
val sv = A.staticVariable
if (sv == 0) {
//...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论