kotlinreflectionkotlin-null-safetykotlin-reflect

Is there a way to check if kotlin class property was defined as nullable at runtime?


I have the following simple class structure:

package qwerty

import kotlin.reflect.full.declaredMemberProperties

class UserSet(
    var user1: User,
    var user2: User? = null,
)

class User(
    var id: Long
)

fun main(args: Array<String>) {
    val type = UserSet::class
    type.declaredMemberProperties // ???
}

In UserSet the first user is non-null, while the second is nullable. There definetly should be a way how to check if a property was defined as nullable at runtime having KClass object, but i don't have an idea how to do it.

I found isMarkedNullable in outType in _descriptor in idea evaluate window during debug, but i can't get access to it from my code.

So the question is how to check if properties of a class defined as nullable in runtime?

enter image description here enter image description here


Solution

  • You can use isMarkedNullable on the property's type. Note that isMarkedNullable is a property of KType, not KClass. Whether or not you write ?, it's the same KClass.

    val type = UserSet::class
    for (property in type.declaredMemberProperties) {
        println("${property.name} - ${property.returnType.isMarkedNullable}")
    }
    

    Output:

    user1 - false
    user2 - true