Search code examples
kotlin

KProperty1: check lateinit property is initialized


When I working with KProperty1, can I check that property is initialized? Now I just trying to call it property and do check for an exception:

inline fun <reified T : Any> T.stringify() =
    T::class
        .memberProperties
        .filter { it.visibility == KVisibility.PUBLIC }
        .filter {
            try {
                it.get(this)
                true
            } catch (_: Throwable) {
                // lateinit property may be not initialized
                // did not find how to check it
                false
            }
        }
        .joinToString(", ") { "${it.name} = \"${it.get(this)}\"" }
        .let { T::class.simpleName + "($it)" }

Solution

  • The backing field of an uninitialised lateinit var will have a value of null, so you can check that:

    The second filter would look like this:

    .filter { !it.isLateinit || it.javaField?.get(this) != null }
    

    Since lateinits always have a backing field, and cannot be of a nullable type, javaField will always be non-null, and get returning null must mean that the property has not been initialised, as opposed to the property being actually initialised to a null value.