0

For my code I am passing in this for the context. This is in mainActivity.kt file

enter image description here
This is the error I am getting in my constructor I am calling it like this

class ForecastAdapter(val forecast: Forecast, val context: Context) : RecyclerView.Adapter<ForecastData>(){

and then I am passing it in the class like this:

runOnUiThread {
   view.adapter = ForecastAdapter(weather, this)
}

So I have no idea why this isn't working for context. I am new to Kotlin and new to android dev so I am little confused right now.

tynn
  • 38,113
  • 8
  • 108
  • 143
Zubair Amjad
  • 621
  • 1
  • 10
  • 29
  • That's because this is not the activity/fragment inside the runOnUiThread block. Use `this@MyActivity` – Luca Nicoletti Oct 19 '18 at 07:29
  • can you try passing 'this@MainActivity'? – Ankit Mehta Oct 19 '18 at 07:30
  • I did and it did work! But why passing `this@MainActivity` works? – Zubair Amjad Oct 19 '18 at 07:32
  • because `this` always refers to the object of the block you are currently in. You can't see it because kotlin lambda magic hides it, but you pass an anonymous class with one implemented function to runOnUiThread. `this` refers to that – Tim Oct 19 '18 at 07:41
  • very similar: https://stackoverflow.com/questions/43617361/runonuithread-is-not-calling the `this` inside the `{}` is actually a `Runnable` as you can see in the answer there – zapl Oct 19 '18 at 07:52
  • Could you post all your ForecastAdapter's constructor and you MainActivity.kt's code?I've tried the same situation and I found that 'this' was worked fine. – aolphn Oct 19 '18 at 12:29

1 Answers1

1

What you're observing is called SAM Conversion. Basically you're implementing a Runnable within your {} block. Therefore this refers to the inner class and to access the outer class you have to add the outer qualified scope this@MainActivity to it.

runOnUiThread { view.adapter = ForecastAdapter(weather, this@MainActivity) }

This is actually the same as

val runnable = Runnable { view.adapter = ForecastAdapter(weather, this@MainActivity) }
runOnUiThread(runnable)
tynn
  • 38,113
  • 8
  • 108
  • 143