Reputation: 2060
I am learning Kotlin. As per I learnt, extension functions provides the ability to extend a class with new functionality without having to inherit from the class. I am creating extension function for okhttp3.RequestBody
. But I am not able to get method in my activity.
Here is my extension function:
fun RequestBody.createPlainRequestBody(message: String): RequestBody = RequestBody.create(MediaType.parse("text/plain"), message)
while calling function as below I am getting unresolved function
RequestBody.createPlainRequestBody()
while I am creating extension function for toast I am getting perfect result as below:
fun Context.showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
by calling:
[email protected]("Upload successfully")
Can any one guide for how to resolve this?
Upvotes: 2
Views: 803
Reputation: 1086
Unfortunately, you cannot do this in
OkHttp
version 3, however, you will able to do this inOkHttp4
which is being rewritten completely in Kotlin, so all the classes will be compatible with Koltin.
You have to extends to its companion object. (You need to make sure that class has a companion object associated with it)
fun RequestBody.Companion.createPlainRequestBody(message: String): RequestBody {
return RequestBody.create(MediaType.parse("text/plain"), message)
}
And after that, you will be able to call it directly from its class.
RequestBody.createPlainRequestBody("message")
Or
RequestBody.Companion.createPlainRequestBody("message")
A companion object is a normal object that associated with or belongs to the class it's similar to static
object in Java. In Kotlin, it's called companion object
.
Upvotes: 1
Reputation: 10733
Extension functions can be applied to instances of a particular class, but you're trying to call it on a class, as if it were a static method. Moreover, your extension function expects an argument and you're not providing any.
What you need in your case is a simple function that creates a RequestBody
as you're not acting on any particular instance of RequestBody
.
Under the hood an extension function is simply a static method where the first argument is the receiver object and any other argument is shifted by one. Your showToast
extension function is equivalent to the following Java snippet:
public static void showToast(Context receiver, String message) {
Toast.makeText(receiver, message, ...).show();
}
That's why you can call Kotlin extension functions from Java.
Upvotes: 5