0

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.

Tayyab Mazhar
  • 1,560
  • 10
  • 26
  • This is answered [here](https://stackoverflow.com/questions/37618738/how-to-check-if-a-lateinit-variable-has-been-initialized).  — However, in this case, an alternative would be to remove the `lateinit` and instead declare it `val user: User by lazy { User }`.  That's shorter, clearer, immutable, and avoids any threading issues. – gidds Dec 05 '20 at 18:01
  • @gidds user.isInitialized gives error when used in init{} – Tayyab Mazhar Dec 05 '20 at 18:09
  • 1
    I found an easy way to check the initialized status https://stackoverflow.com/a/60598065/9026710. – Tayyab Mazhar Dec 05 '20 at 18:47
  • the syntax is ``::user.isInitialized``, with the ``::`` (like function references – cactustictacs Dec 06 '20 at 09:29

1 Answers1

1

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()
Jakob
  • 141
  • 1
  • 13