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)

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

stackoverflow.com/questions/36623177/…\You can go through this to know which is appropriate to use lateinit or lazy initialisation
This needs to be a var though
i changed val to var
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...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.