Static Methods 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 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 *