How to check outside the companion object if a lateinit var inside it is initialized

1.3k Views Asked by At

How do I check if user variable is initialized when an instance of MyClass is created?

class MyClass
{
    companion object
    {
        lateinit var user:User
    }

    init
    {
        //initialize if not initialized
        //user.isInitialized
        user = User
    }
}

What I want to do is initialize the variable only when the 1st instance of MyClass is created, and the same value of this variable should be accessible across all instances.If it's not possible to use isInitialzed like this, then a workaround is acceptable as well.

1

There are 1 best solutions below

0
On

Just use a nullable variable.


  1. Unsafe approach (unsafe in the same way as lateinit):
class MyClass {
    companion object {
        val user get() = user_ ?: throw UninitializedPropertyAccessException("property has not been initialized")
        private var user_: User? = null
    }

    init {
        if (user_ == null) user_ = User()
    }
}

Now you can access the property:

MyClass.user.example()

  1. Safe approach:
class MyClass {
    companion object {
        var user: User? = null; private set
    }

    init {
        if (user == null) user = User()
    }
}

Now you can access the property in a safe way:

MyClass.user?.example()