David Cuesta
03/15/2019, 1:22 PMDico
03/15/2019, 1:24 PM/**
* 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>()
David Cuesta
03/15/2019, 1:24 PMDico
03/15/2019, 1:24 PMlateinit var a: String
After:
var a: String = lateinit()
diesieben07
03/15/2019, 1:25 PM::a.isInitialized
wbertan
03/15/2019, 1:25 PMif (::lateVar.isInitialized)
diesieben07
03/15/2019, 1:25 PMDico
03/15/2019, 1:25 PMFredrik Larsen
03/15/2019, 1:25 PMDico
03/15/2019, 1:25 PMDavid Cuesta
03/15/2019, 1:26 PMDico
03/15/2019, 1:26 PMFredrik Larsen
03/15/2019, 1:28 PMdiesieben07
03/15/2019, 1:28 PMclass Foo {
companion object {
lateinit var foo: String
val fooInitialized get() = ::foo.isInitialized
}
}
fun main() {
println(Foo.fooInitialized)
}
David Cuesta
03/15/2019, 1:28 PMDavid Cuesta
03/15/2019, 1:29 PMdiesieben07
03/15/2019, 1:29 PMdiesieben07
03/15/2019, 1:30 PMDavid Cuesta
03/15/2019, 1:31 PMstreetsofboston
03/15/2019, 1:58 PMisInitialized
, you should consider a nullable type instead and use the ?.
syntax.David Cuesta
03/15/2019, 2:16 PM