Kotlin: 在抽象类中在继承类之间共享变量

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

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) {
    //...
}

huangapple
  • 本文由 发表于 2020年5月2日 16:03:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61556192.html
匿名

发表评论

匿名网友

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

确定