https://kotlinlang.org logo
#announcements
Title
# announcements
r

robstoll

11/17/2020, 8:07 PM
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

Arkadii Ivanov

11/17/2020, 8:51 PM
Something like this?
inline fun <reified T> isNullable(): Boolean { return typeOf<T>().isMarkedNullable }
r

robstoll

11/17/2020, 8:53 PM
sweet 👍 thanks
i

ilya.gorbunov

11/18/2020, 8:39 AM
if (null is T)
Checks whether null belongs to
T
type that can be only if
T
is nullable.
👍 2
mind blown 1
r

robstoll

11/19/2020, 6:41 AM
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

ilya.gorbunov

11/19/2020, 10:00 AM
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.
2 Views