Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialized objects are always created

Tags:

android

kotlin

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)
like image 280
AswathyShaji Avatar asked Mar 20 '26 19:03

AswathyShaji


2 Answers

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

like image 144
Arjun Avatar answered Mar 22 '26 08:03

Arjun


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...)

like image 43
Rafa Avatar answered Mar 22 '26 07:03

Rafa