Home > front end >  Kotlin Type mismatch: inferred type is String but Unit was expected
Kotlin Type mismatch: inferred type is String but Unit was expected

Time:09-18

Im trying to get the return result to return a string, I believe this might be a noob question but I'm very new to kotlin so please don't be harsh. All solutions welcome!

private val client = OkHttpClient()

    fun getRequest(id: String) {
        val url = "http://localhost:8000/api/v1/discord?discordid=$id"
        val request = Request.Builder()
            .url(url)
            .header("User-Agent", "OkHttp Bot")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                println("Error: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
                    var result = response.body!!.string()
                    return result

                }
            }
        })
}

CodePudding user response:

onResponse function has no return type. If you trying to return some value it will throw some error. So if you want do somthing with the response, you can create a method and pass response body as paramter and do anything with that.

 override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
                    
                    var result = response.body?.string()?:""
                    someMethod(result)
                }
            }


fun someMethod(response:String){
//Update UI here
}
  • Related