Most of the programming language have concepts where classes can have static members. Namely — fields that are only created once per class and can be accessed without an instance of their containing class.
Kotlin doesn’t support static keyword. It means that you can’t create a static method and static variable in Kotlin class. Fortunately, Kotlin object can handle this. by declaring a companion object inside your class.
The companion object is a singleton, and its members can be accessed directly via the name of the containing class (although you can also insert the name of the companion object if you want to be explicit about accessing the companion object):
class MyClass {
companion object {
val info = "This is info"
fun getMoreInfo():String { return "This is more fun" }
}
}
MyClass.info // This is info
MyClass.getMoreInfo() // This is more fun
In spite of this syntactical convenience, the companion object is a proper object on its own, and can have its own supertypes – and you can assign it to a variable and pass it around. If you’re integrating with Java code and need a true static
member, you can annotate a member inside a companion object with @JvmStatic
A companion object is initialized when the class is loaded (typically the first time it’s referenced by other code that is being executed), in a thread-safe manner. You can omit the name, in which case the name defaults to Companion
. A class can only have one companion object, and companion objects can not be nested.
@JvmStatic and @JvmField in companion of interfaces
With Kotlin 1.3 (update 2019), it is possible to mark members of a companion
object of interfaces with annotations @JvmStatic
and @JvmField
. In the classfile, such members will be lifted to the corresponding interface and marked as static
.
For example, the following Kotlin code:
interface Foo {
companion object {
@JvmField
val answer: Int = 42
@JvmStatic
fun sayHello() {
println("Hello, world!")
}
}
}
It is equivalent to this Java code:
interface Foo {
public static int answer = 42;
public static void sayHello() {
// ...
}
}
To sum up
Creating static members for a Kotlin class is not difficult but somehow unfamiliar to most of us. Nevertheless, we are able to call its members with the same syntax as calling static methods in Java or C#. (using the class name as a qualifier).
Refer this article for a quick Kotlin reference.