static-methodskotlin

Static extension methods in Kotlin


How do you define a static extension method in Kotlin? Is this even possible? I currently have an extension method as shown below.

public fun Uber.doMagic(context: Context) {
    // ...
}

The above extension can be invoked on an instance.

uberInstance.doMagic(context) // Instance method

but how do I make it static method like shown below.

Uber.doMagic(context)         // Static or class method

Solution

  • To achieve Uber.doMagic(context), you can write an extension to the companion object of Uber (the companion object declaration is required):

    class Uber {
        companion object {}
    }
    
    fun Uber.Companion.doMagic(context: Context) { }
    

    EDIT

    If the class is a Java class, it is not possible to add a static extension method. See https://youtrack.jetbrains.com/issue/KT-11968