在 kotlin 中创建扩展函数的先决条件

Prerequisite to create extension function in kotlin

我正在学习 Kotlin。据我了解,扩展函数提供了使用新功能扩展 class 的能力,而无需继承 class。我正在为 okhttp3.RequestBody 创建扩展函数。但是我无法在 activity.

中获取方法

这是我的扩展函数:

fun RequestBody.createPlainRequestBody(message: String): RequestBody = RequestBody.create(MediaType.parse("text/plain"), message)

在如下调用函数时我得到了未解析的函数

RequestBody.createPlainRequestBody()

当我为 toast 创建扩展函数时,我得到了如下完美的结果:

fun Context.showToast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

通过调用:

this@MainActivity.showToast("Upload successfully")

任何人都可以指导如何解决这个问题吗?

扩展函数可以应用于特定 class 的实例,但您正试图在 class 上调用它,就好像它是静态方法一样。此外,您的扩展函数需要一个参数,而您没有提供任何参数。

在您的案例中,您需要的是一个创建 RequestBody 的简单函数,因为您没有对 RequestBody 的任何特定实例进行操作。

在引擎盖下,扩展函数只是一个静态方法,其中第一个参数是接收者对象,任何其他参数都移动一个。您的 showToast 扩展函数等同于以下 Java 片段:

public static void showToast(Context receiver, String message) {
    Toast.makeText(receiver, message, ...).show();
}

这就是为什么您可以从 Java 调用 Kotlin 扩展函数的原因。

Unfortunately, you cannot do this in OkHttp version 3, however, you will able to do this in OkHttp4 which is being rewritten completely in Kotlin, so all the classes will be compatible with Koltin.

你必须扩展到它的伴生对象。 (您需要确保 class 有与之关联的伴生对象)

fun RequestBody.Companion.createPlainRequestBody(message: String): RequestBody {
   return RequestBody.create(MediaType.parse("text/plain"), message)
}

之后,您将可以直接从其class调用它。

RequestBody.createPlainRequestBody("message")

RequestBody.Companion.createPlainRequestBody("message")

伴随对象是与 class 关联或属于 class 的普通对象,类似于 Java 中的 static 对象。在 Kotlin 中,它被称为 companion object.