Reputation: 936
I have this kotlin function I am using to access data after making a http request using the fuel
library in android, from a tutorial I am following but certain parts of this function are strange to me as I am learning kotlin:
fun search(term: String, skip: Int, take: Int, responseHandler: (result: WikiResult) -> Unit?) {
Urls.getSearchUrl(term, skip, take).httpGet()
.responseObject(WikipediaDataDeserializer()) { _, response, result ->
if (response.statusCode != 200) {
throw Exception("Unable to get articles")
}
val(data, _) = result
responseHandler.invoke(data as @ParameterName(name = "result") WikiResult)
}
}
These I understand so far:
responseHandler: (result: WikiResult) -> Unit?
: anonymous function that returns nothingbut I can't understand most of this part:
.responseObject(WikipediaDataDeserializer()) { _, response, result ->
if (response.statusCode != 200) {
throw Exception("Unable to get articles")
} #<-- this I know throws an exception if the response isn't a 200
val(data, _) = result
responseHandler.invoke(data as @ParameterName(name = "result") WikiResult)
}
Upvotes: 0
Views: 83
Reputation: 8191
responseHandler: (result: WikiResult) -> Unit?
is a callback (lambda) function.
It says that it will take in a result: WikiResult
and give this to whatever is calling it.
.responseObject(WikipediaDataDeserializer()) { _, response, result ->
if (response.statusCode != 200) {
throw Exception("Unable to get articles")
} #<-- this I know throws an exception if the response isn't a 200
val(data, _) = result
responseHandler.invoke(data as @ParameterName(name = "result") WikiResult)
}
here, where you are calling responseObject(WikipediaDataDeserializer())
, you are specifying how to handle another lambda function.
{ _, response, result ->
is simply saying that you are getting 3 values, the first one you don't care for, you're not using it, so you can rename it to _
, then your response
object and your result
object you will be using, so they have been given those names accordingly.
Edit
you have to look at it like 2 different methods :
when you call search
, you'll do this :
search("term", 0, 0) {
//this is your responseHandler: (result: WikiResult) -> Unit?)
// in here, you'll get a result: WikiResult
}
similarly, when you call this :
Urls.getSearchUrl(term, skip, take).httpGet()
.responseObject(WikipediaDataDeserializer()) { _, response, result -> ...
this entire chain has a callback you get back, and it gives you 3 values, as explained in my answer above.
val(data, _) = result
is known as Destructuring Declarations
https://kotlinlang.org/docs/reference/multi-declarations.html
but yes, you're correct in your understanding, we are using the response of this callback, destructing it and then triggering the callback with this data
Upvotes: 1