What am I doing wrong using LET (Kotlin)?

Asked

Viewed 99 times

1

I’m using retrofit and onResponse, when I try to get body information with (Let), the internal code is not executed.

response?.body()?.let {
  Log.i("Info", "Cidades: " + it.size)
}

If you try it like that, it won’t work either:

response?.body()?.let {
  Log.i("Info", "Cidades: " + it.size)
}

But if I put it like that, it works:

if (response != null) {
  if (response.body() != null){
     Log.i("Info", "Cidades: " + response.body()?.size)
  }
}

What am I missing? The whole code is below.

call.enqueue(object: Callback<List<Cidade>?> {
    override fun onResponse(call: Call<List<Cidade>?>?, response: Response<List<Cidade>?>?) {
        /*Not working - Does Not execute Log*/
        response?.let {
            Log.i("Info", "Cidades: " + it.body()?.size)
        }

        /*Working - Does execute Log*/
        if (response != null) {
            if (response.body() != null){
                Log.i("Info", "Cidades: " + response.body()?.size)
            }
        }
    }

    override fun onFailure(call: Call<List<Cidade>?>?, t: Throwable?) {
        var error = t?.message.toString()
        Log.e("error", error)

        txtErrorMessage.text = error
        txtErrorMessage.visibility = View.VISIBLE
    }
})
  • Here the let both ways worked as expected. A tip: your if may be simplified as follows:: if (response?.body() != null) {.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.