In this tutorial, you shall learn how to write a static method in a class in Kotlin, with examples.

Static Method in Kotlin

Unlike Java, we do not have a static keyword in Kotlin. But, that does not limit us to write methods in Kotlin that function as static methods in Java.

To achieve the functionality of a static method in Kotlin, use companion keyword modifier.

Example

In the following example, we define a class MyClass with with a function greetings(), where the function is modified using companion keyword. We can call this method using Class name as MyClass.greetings().

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    MyClass.greetings()
}

class MyClass {
    companion object {
        fun greetings() {
            print("Hello World!")
        }
    }
}

Output

Hello World!

Conclusion

In this Kotlin Tutorial, we learned how to call a method using Class name, without instantiating an instance of the class type.