Search code examples
androidvariableskotlinstaticvar

How to define a public static Boolean in Kotlin


I wanted to know how I define a static variable in Kotlin that can be used in other classes that do not final. Because the data is changing.

Example Java:

public static Boolean ActivityIsRuning = false;

Solution

  • There are three ways to achieve this:

    1) Top-level / global declaration

    Declare a variable outside of any class or function and it will be accessible from anywhere:

    var activityIsRunning = false
    

    2) object (an out of the box singleton)

    object StaticData {
        var activityIsRunning = false
    }
    

    Accessable like this:

    StaticData.activityIsRunning
    

    3) Class with companion object (as Todd already suggested)

    class Config {
        companion object {
            var activityIsRunning = false
        }
    }
    

    Accessable like this:

    Config.activityIsRunning