A.I, Data and Software Engineering

How to create Static Members for a Kotlin class

Kotlin programming language
Kotlin programming language

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):

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:

It is equivalent to this Java code:

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.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest


You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.