Reputation: 369
I have function which doesn't return any:
fun getName(name:String){
val requestUrl =
"https://api/app/getherp"
val resRequest =object :JsonObjectRequest(
Request.Method.GET, requestUrl,null,
{ response ->
},
{ error ->
}
)
queue.add(resRequest)
}
I want return value getName's function like this:
fun getNorm(name: String): String {
return getName(name)
}
but I get error:
Type mismatch.
Required:
String
Found:
Unit
I know that if I add .toString
to return getName(name)
- this is not enough. Because in this case I get as result kotlin.Unit
. What have I to do?? Thank you
UPD: as advice here I added synchronous code. But result is the same. My code is now:
fun getName(
name: String,
requestResult: (res: JSONObject) -> Unit,
requestError: ((err: String) -> Unit)? = null
) {
val requestUrl = "https://api/app/getherp"
val jsonObjectRequest = object : JsonObjectRequest(Request.Method.GET, requestUrl, null,
{ response ->
requestResult(response)
},
{ error ->
requestError?.invoke(error.toString());
}
) {
override fun getHeaders(): MutableMap<String, String> {
return getAuthHeaders()
}
}
queue.add(jsonObjectRequest)
}
and I call this function like this:
fun getNamePers(
name: String, result: (res: JSONObject) -> Unit,
error: ((err: String) -> Unit)? = null
) {
MyClass.getName(name, result, error)
}
Upvotes: 2
Views: 2028
Reputation: 76579
fun getName(name:String)
would need to return String
in a synchronous manner. As this doesn't seem to be possible with JsonObjectRequest
, I'd question the whole approach. fun getNorm(name: String): String
also appears quite superfluous, as it only wraps the other one method.
You'd need to move your code into { response -> ... }
- or call a method from there.
See Asynchronous Programming Techniques for a more detailed explanation.
When setting a few break-points, the order of execution merely explains itself.
Upvotes: 2
Reputation: 576
Function getNorm
should return String but it returns getName
and expects getName function to return a String, but getName
function doesn't return anything which is why it is giving unit error, either remove the return type String, or return the string which you need from getName
Upvotes: 2