Static extension methods in Kotlin

Ragunath Jawahar picture Ragunath Jawahar · Jan 29, 2015 · Viewed 39.7k times · Source

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

Answer

Andrey Breslav picture Andrey Breslav · Nov 22, 2015

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) { }