kotlin reflection check nullable types

前端 未结 1 1065
萌比男神i
萌比男神i 2021-01-12 17:37

How can I test if a KType variable holds a value of a nullable kotlin type, (e.G. Int?)?

I have

var type: KType 

variable coming fr

1条回答
  •  臣服心动
    2021-01-12 18:21

    As you can see from the KType API documentation, its interface is far from complete. Currently almost for any operation you have to resort to Java reflection with the .javaType extension property available on KType instances. (By the way, this is surely going to be addressed in Kotlin 1.1.)

    In your case, you have to check if the type is nullable and its Java type is equal to that of the required primitive class, e.g.:

    val isNullableInt = type.isMarkedNullable &&
                        type.javaType == Int::class.defaultType.javaType
    

    I can also present a funny workaround which may be more suitable for your use case: you can declare a private function with the needed type and use reflection to compare against the return type of that function at runtime:

    // Only return type of this function is used
    fun _nullableInt(): Int? =
        TODO()  // Doesn't matter, it never gets called
    
    ...
    
    val isNullableInt = type == ::_nullableInt.returnType
    

    0 讨论(0)
提交回复
热议问题