3

In some case my broadcast receiver is not required and so need to check if the receiver is null or not but somehow this object is not null even if not using it and causing crash.

private val myBroadCastReceiver by lazy {
   MyBroadcastReceiver()
}
if(myBroadCastReceiver != null) unregisterReceiver(myBroadCastReceiver)
AswathyShaji
  • 73
  • 3
  • 11

2 Answers2

5

when you are trying null check, its initialised and thus it not null. Try this this instead of lazy.

private var myBroadCastReceiver : MyBroadcastReceiver? = null

or try this answer Kotlin: Check if lazy val has been initialised

Arjun
  • 358
  • 2
  • 13
4

Because you declare myBroadcastReceiver as Lazy, that means that you won't use it until you call MyBroadcastReceiver(). Which you do in your if statement.

So if you check it that way, it won't be null, because you actually execute MyBroadcastReceiver() here if(myBroadCastReceiver...)

Rafa
  • 3,219
  • 4
  • 38
  • 70