Static Classes in Kotlin

There is no static keyword in the Kotlin language, so what do you do when you want a static (nested) class, method or field in Kotlin?

Static Classes in Kotlin

In Java, you can use static nested classes to instantiate inner classes without instantiating the outer class. In Kotlin, nested classes are static by default, so its data members and member functions can be accessed without creating an object of the outer class. Nested classes access the data member of outer classes. See the example below:

class OuterClass(val name: String) {

    class NestedClass

    inner class InnerClass {
        fun formatName() = name.toUpperCase()
    }
}

val outer = OuterClass("test1")
val nested = OuterClass.NestedClass()

val result = OuterClass("test2").InnerClass().formatName() // == Test2

As you can see in the example about, Kotlin has standard classes (OuterClass), nested classes (NestedClass, which is the equivalent of Java’s static class) and InnerClass, indicated by the inner keyword modifier).

Static Methods in Kotlin

There are a couple of ways to have the equivalent of Java’s static method in Kotlin. The most common way is to put to those methods into a companion object, like this:

class MyClass {
    companion object {
        fun format(input: String) = "<${input}>"
    }
}

val formatted = MyClass.format("hello") // == <hello>

However, when calling this method from Java, you’ll need to place the Companion identifier between the class name and method name, like this:

MyClass.Companion.format("hello")

To prevent that, you can annotate the format method with the @JvmStatic annotation, like this:

    companion object {
        @JvmStatic
        fun format(input: String) = "<${input}>"
    }

That way, you can call the method from Java just like a normal Java static method:

MyClass.format("hello")

Leave a Reply

Your email address will not be published. Required fields are marked *