Louis Wasserman
Louis Wasserman

Reputation: 198211

Detecting nullability within reified types

As discussed in this question, you can detect if a reified type includes null:

inline fun <reified T> isTNullable() = null is T

However, I wish to make an even more complex query, which I'm not sure is possible: testing if a reified type T is a Pair and which, if any, of its components is nullable. I want a method with the following properties:

inline fun <reified T> nullabilityOfPairComponents(): Pair<Boolean, Boolean>?

nullabilityOfPairComponents<Int>() == null
nullabilityOfPairComponents<Pair<Int?, String>> = Pair(true, false)
nullabilityOfPairComponents<Pair<Int?, String?>> = Pair(true, true)

Is this possible? I observe that KTypes have a nullability component, but it seems that we can only currently retrieve a KClass, not a KType, from reified types.

Note that we cannot use tricks like <reified A, reified B, T : Pair<A, B>>, because this method must accept arbitrary types (the <Int> example).

Upvotes: 3

Views: 73

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

With experimental APIs, it is certainly possible:

@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T : Any> nullabilityOfPairComponents(t: T): Pair<Boolean, Boolean>? {
  if (T::class.java != Pair::class.java) return null
  val (t1, t2) = typeOf<T>().arguments
  return Pair(
      t1.type!!.isMarkedNullable,
      t2.type!!.isMarkedNullable
  )
}

This depends on the experimental typeOf method.

Upvotes: 2

Related Questions