Hey guys, anyone knows how can I check if a latein...
# announcements
d
Hey guys, anyone knows how can I check if a lateinit var is initialized from a function of the same class where the lateinit var resides?
d
That's not possible without using reflection or any other way of accessing the backing field directly. I have a workaround though which looks like this. lateinit.kt
Copy code
/**
 * This function will always return null, but the compiler doesn't understand that.
 *
 * To be used instead of lateinit modifier,
 * where one wishes to check if the property was initialized,
 * or where one wishes to avoid the null check inserted in the getter.
 *
 * @throws NullPointerException if T is a concrete, that is, not generic, primitive type.
 */
@Suppress("UNCHECKED_CAST")
fun <T : Any> lateinit(): T = (nullPropInstance as Lateinit<T>).value


private class Lateinit<T : Any> {
    val value: T = run { value }
}

private val nullPropInstance = Lateinit<Any>()
d
Thank you @Dico
d
Before:
lateinit var a: String
After:
var a: String = lateinit()
d
::a.isInitialized
☝️ 3
w
if (::lateVar.isInitialized)
d
does not require reflection.
d
oh that's a thing 😂
f
this::foo.isInitialized
d
I feel dumb
d
the property that I want to check is inside a companion object and isInitialized doesn't work
d
I don't recommend using that code then. You lose the exception message saying you accessed a lateinit property before it's initialized.
f
You can make a function in your companion object that returns it then, since you can't access the backing field safely at that time.
d
Copy code
class Foo {
  companion object {
    lateinit var foo: String
    val fooInitialized get() = ::foo.isInitialized
  }
}

fun main() {
  println(Foo.fooInitialized)
}
d
thank you, I like that solution
what do you recommend to wait until the variable is initialized? Using just a while? or another solution?
d
Don't use lateinit, use a property with custom setter.
Then you know exactly when it's set
d
The lateinit var is going to be initialized when the class is instantiated ( is initialized in the constructor) and the lateinit var resides in the companion object
s
My experience is that if you need to check for something like
isInitialized
, you should consider a nullable type instead and use the
?.
syntax.
d
yep.. I am doing that right now after some attempts