3

I want to check the lateinit propery initialized or not inside an extension method. I want to execute simple function call to lateinit property safely inside an extenstion method.

I can use this::property.isInitialized.

Want to write some extension like:

fun <T> T?.executeSafety(func: T.() -> (Unit)) { this?.func() }

Then we can easily execute simple methods on lateinit property. Please help on this

vishnu benny
  • 998
  • 1
  • 11
  • 15

1 Answers1

1

On Kotlin 1.2 and up, we can quickly check whether a lateinit property has been initialised or not using a reflection based API.

Here's how it works:

lateinit var fullName: String

if (::fullName.isInitialized) {
    print("Hi, $fullName")
}

Since this reflection API works only on properties which are defined:

  • In the same class where the check is being made
  • In an outer class
  • As top-level in the same file

We can check lateinit properties of other classes by adding a new method on the target class:

class LateComer {
    lateinit var student: Student

    fun isStudentInitialised() = ::student.isInitialized
}
Haroon
  • 538
  • 2
  • 11
  • **lateinit** means late initialization. If you do not want to initialize a variable in the constructor instead you want to initialize it later on and if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. It will not allocate memory until initialized. – Haroon May 25 '20 at 08:52
  • If we can write an extension that will check the initialisation then we can avoid check at every place right? And please mind that generics are introduced to avoid rewrite same code. – vishnu benny May 25 '20 at 08:53
  • 3
    "then we can avoid check at every place" If you need to check at many places, then it probably shouldn't be `lateinit`; just go with a nullable property and use `?.`. – Alexey Romanov May 25 '20 at 14:18
  • I've edited the answer to include a better approach – Haroon May 26 '20 at 19:06
  • 1
    this is a good complete answer – Ahmed Nabil Apr 04 '23 at 12:28