Static extension methods in Kotlin

2020-01-30 08:19发布

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

7条回答
干净又极端
2楼-- · 2020-01-30 08:49

To create an extension method in kotlin you have to create a kotlin file(not a class) then declare your method in the file Eg:

public fun String.toLowercase(){
    // **this** is the string object
}

Import the function in the class or file you are working on and use it.

查看更多
登录 后发表回答