Kotlin: Unresolved local class when using BroadcastReceiver in Activity
Looks like some bug and I think it should be on Kotlin issue tracker, but I guess that you can fix it for now by defining receiver as a class:
abstract class BaseActivity : Activity {
companion object {
private const val LOG_TAG = "BaseActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,
IntentFilter(MY_FILTER))
}
override fun onStop() {
super.onStop()
if(isFinishing){
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
}
}
private val broadcastReceiver = MyBroadcastReceiver()
inner class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) = when (intent?.action) {
MY_FILTER -> Log.d(LOG_TAG, "This is my filter!")
else -> Log.e(LOG_TAG, "Hello action ${intent?.action}")
}
}
}
The fix is to specify the exact type of your variable, type inference isn't working in this case for some reason (probably a Kotlin bug).
So instead of this:
private val broadcastReceiver = object : BroadcastReceiver()
Use this:
private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver()