In Kotlin, you can declare static methods and variables using the companion object
keyword within a class. Kotlin does not have the static
keyword like some other languages, but it achieves the same effect with companion object
. Here's how you can define static methods and variables in Kotlin:
Static Variables (Properties) using companion object
:
class MyClass { companion object { const val staticVariable = "I'm a static variable" } } // Access the static variable val value = MyClass.staticVariable
In this example, staticVariable
is a static property (a constant in this case) declared inside the companion object
of the MyClass
class. You can access it using the class name, as shown in the comment.
Static Methods using companion object
:
class MyClass { companion object { fun staticMethod() { println("I'm a static method") } } } // Call the static method MyClass.staticMethod()
Here, staticMethod
is a static function declared within the companion object
. You can call it using the class name.
You can also give the companion object
a name if you prefer:
class MyClass { companion object MyCompanion { const val staticVariable = "I'm a static variable" fun staticMethod() { println("I'm a static method") } } } // Access the static variable and call the static method val value = MyClass.MyCompanion.staticVariable MyClass.MyCompanion.staticMethod()
Using companion object
, you can group static members together and access them through the class name without the need to create an instance of the class. This is Kotlin's way of achieving the same functionality as static members in other languages.
eclipse-plugin gridfs clang hibernate-annotations morphological-analysis angular-observable lint nfs google-material-icons line-numbers