Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting nullability within reified types

Tags:

kotlin

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).

like image 710
Louis Wasserman Avatar asked Apr 23 '26 12:04

Louis Wasserman


1 Answers

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.

like image 66
Louis Wasserman Avatar answered Apr 25 '26 00:04

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!