0

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.