You can check nullability with isMarkedNullable
. The following code:
class MyClass(val nullable: Long?, val notNullable: MyClass)
MyClass::class.declaredMemberProperties.forEach {
println("Property $it isMarkedNullable=${it.returnType.isMarkedNullable}")
}
将打印:
Property val MyClass.notNullable: stack.MyClass isMarkedNullable=false
Property val MyClass.nullable: kotlin.Long? isMarkedNullable=true
摘自documentation(我的重点):
对于Kotlin类型,这意味着允许使用null值
Note that even if isMarkedNullable
is false, values of the type can
still be null
. This may happen if it is a type of the type parameter
with a nullable upper bound:
fun <T> foo(t: T) {
// isMarkedNullable == false for t's type, but t can be null here
}