What I'm forgetting while using LET?


#1

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

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

If I try this, it doesn’t work either:

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

But if I try to check if it’s null, the code runs:

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

What I’m missing?


#2

What is the exact error shown?


#4

None, the code inside (Let) just doesn’t execute. Here is the whole code.

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

                /*Workin*/
                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
            }
        })

#5

What does the working code prints?


#6

That’s the problem, it doesn’t print anything, the code just doesn’t get inside the (Let) clause, the code continues to run.


#7

This works

fun main(args: Array<String>) {
    val response = Response
    response?.body()?.let {
        println("Cidades: " + it.size)
    }
}

object Response {
    fun body() = listOf(1, 2, 3)
}

Try it yourself https://try.kotlinlang.org/