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?
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?
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
isMarkedNullablereturns false , the type values can still benull. 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).
Source: https://ru.stackoverflow.com/questions/583314/
All Articles