I wonder if there is a way to check if a lateinit
variable has been initialized. For example:
class Foo() {
private lateinit var myFile: Fi
If you have a late init
property in one class and need to check if it is initialized from another class
if(foo::file.isInitialized) // this wouldn't work
The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.
Example:
class Foo() {
private lateinit var myFile: File
fun isFileInitialised() = ::file.isInitialized
}
// in another class
class Bar() {
val foo = Foo()
if(foo.isFileInitialised()) // this should work
}
There is a lateinit
improvement in Kotlin 1.2 that allows to check the initialization state of lateinit
variable directly:
lateinit var file: File
if (this::file.isInitialized) { ... }
See the annoucement on JetBrains blog or the KEEP proposal.
UPDATE: Kotlin 1.2 has been released. You can find lateinit
enhancements here: