最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - KProperty1: check lateinit property is initialized - Stack Overflow

programmeradmin8浏览0评论

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)" }

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)" }
Share Improve this question asked Feb 5 at 10:25 HettHett 3,8252 gold badges39 silver badges56 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论