Is there a way to know if the type argument passed...
# announcements
r
Is there a way to know if the type argument passed to a
fun <reified T>
is a nullable type? I am asking in the context of https://youtrack.jetbrains.com/issue/KT-8947 I would like to be able to do something like:
Copy code
fun <reified T> foo() = if(T::isNullable) "y" else "n"
foo<Int?>() // returns y
foo<Int>()  // return n
a
Something like this?
inline fun <reified T> isNullable(): Boolean { return typeOf<T>().isMarkedNullable }
r
sweet 👍 thanks
i
if (null is T)
Checks whether null belongs to
T
type that can be only if
T
is nullable.
👍 2
mind blown 1
r
Interesting, was this always like that? I remember that I tried something like that 1 year ago or so and failed. I am asking because I am not using the latest Kotlin version in some projects
i
I suppose it only works for reified T. For non-reified T, it would be an unchecked cast that results in always true or always false, depending on the T upper bound.