How to access static properties in an object in Kotlin

1 Answer

0 votes
class Configuration {
    // companion object houses members that are shared across the class level
    companion object {
        // Private backing field acting as static property
        private var environment: String = "production"

        // A function acting like a static getter to safely access the property
        fun getEnvironment(): String {
            return environment
        }

        // A function acting like a static setter to modify the property with validation
        fun setEnvironment(newEnv: String) {
            if (newEnv.isNotBlank()) {
                environment = newEnv
            }
        }
    }
}

fun main() {
    // 1. Accessing the static-like function/property directly via the Class Name (Best Practice)
    println("Current Environment: ${Configuration.getEnvironment()}")

    // 2. Modifying the static-like property via the companion object setter
    Configuration.setEnvironment("staging")
    println("Updated Environment: ${Configuration.getEnvironment()}")
}


/*
run:

Current Environment: production
Updated Environment: staging

*/

 



answered 6 days ago by avibootz
...