How can we dynamically (that is, during runtime) check whether the field is Nullable?

I tried to google and experiment with the Kotlin and Java classes myself, but nothing happened, maybe someone came across?

    1 answer 1

    Answered in the end in English StackOverflow

    Transfer:

    You can check if null is valid using the isMarkedNullable flag.

    Following code

     class MyClass(val nullable: Long?, val notNullable: MyClass) MyClass::class.declaredMemberProperties.forEach { println("Property $it isMarkedNullable=${it.returnType.isMarkedNullable}") } 

    Prints:

     Property val MyClass.notNullable: stack.MyClass isMarkedNullable=false Property val MyClass.nullable: kotlin.Long? isMarkedNullable=true 

    Excerpt from the documentation (my selection):

    For Kotlin types, this means that null is allowed to represent types. In practice, this means that types will be identified with a question mark ( ? ) At the end. For non-Kotlin types, this means that the type or symbol that will be defined with this type is marked with an annotation of the javax.annotation.Nullable type.

    It is important that even if isMarkedNullable returns false , the type values ​​can still be null . This can happen if type is a parameter type:

     fun <T> foo(t: T) { // isMarkedNullable == false for t's type, but t can be null here } 

    Also, you need to take into account that the field can be marked as NotNull, but it can still have a zero value (as far as I understand, this is due to compatibility issues with Kotlin and other JVM languages).

    • it was worth translating the answer, not just copying - Grundy
    • @Grundy The question is not so important, but I will translate, ok. - Janislav Kornev
    • The point is not the importance of the question, but the fact that it is ruSO, and here not only questions should be in Russian, but also answers. - Grundy