0

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 Answer 1

1

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) {
    //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

A more concise alternative is a top-level variable — defined in the same file but outside any class definitions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.