You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin如何通过reified泛型检测Pair类型及其组件的可空性

该需求完全可以实现,核心依赖Kotlin标准库提供的typeOf<T>()方法(Kotlin 1.3及以上版本支持,1.7版本后正式稳定无需额外配置),该方法可以通过reified泛型直接获取完整的KType实例,包含泛型参数、可空性标记等全部类型信息。

实现代码

import kotlin.reflect.typeOf

inline fun <reified T> nullabilityOfPairComponents(): Pair<Boolean, Boolean>? {
    val type = typeOf<T>()
    // 非Pair类型直接返回null
    if (type.classifier != Pair::class) return null
    val typeArgs = type.arguments
    if (typeArgs.size != 2) return null
    val firstNullable = typeArgs[0].type?.isMarkedNullable ?: return null
    val secondNullable = typeArgs[1].type?.isMarkedNullable ?: return null
    return Pair(firstNullable, secondNullable)
}

效果验证

运行你给出的测试用例可完全匹配预期:

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

如果使用Kotlin 1.3~1.6版本,需要在函数上添加@OptIn(ExperimentalStdlibApi::class)注解即可正常使用。如果需要额外判断外层Pair本身是否可空,可读取type.isMarkedNullable属性自行扩展逻辑。


内容的提问来源于stack exchange,提问作者Louis Wasserman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:06:03