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
Recomend you to look at this link. As you can see there, you just should declare method at the top-level of the package (file):
This is equal to
With constans everything are the same. This declaration
is equal to
I'm also quite fond of having the possibility to add static extension methods in Kotlin. As a workaround for now I'm adding the exntension method to multiple classes instead of using one static extension method in all of them.
This is what the official documentation says:
Kotlin static methods
To achieve
Uber.doMagic(context)
, you can write an extension to the companion object ofUber
(the companion object declaration is required):I actually had this exact question 30 minutes ago, so I started digging around and couldn't find any solution or workaround for this, BUT while searching I found this section on the Kotlinglang website that states that:
So then I had the craziest idea ever, why not define an extension function with a nullable receiver (without actually using that receiver) and then call it on a null object! So I tried that, and it worked pretty well, but it looked so ugly. It was like this:
So I went around that by creating a val in my extensions file of the receiver type that had a value of null and then use it in my other class. So, as an example, here is how I implemented a "static" extension function for the
Navigation
class in Android: In my NavigationExtensions.kt file:In the code that uses it:
Obviously, this isn't a class name, it is just a variable of the class type that has a null value. This is obviously ugly on the extension maker side (because they have to create the variable) and on the developer side (because they have to use the
SType
format instead of the actual class name), but it is the closest that can be achieved right now compared to actual static functions. Hopefully, the Kotlin language makers will respond to the issue that was created and add that feature in the language.You can create a static method with using Companion object like:
and then you can call it like: