Kotlin中的静态扩展方法 [英] Static extension methods in Kotlin

查看:813
本文介绍了Kotlin中的静态扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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

推荐答案

要实现Uber.doMagic(context),您可以编写

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

这篇关于Kotlin中的静态扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆