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

Kotlin实现泛型checkType函数根据入参判断值类型的方法

Kotlin 通用checkType泛型函数实现

直接通过Kotlin内置的is类型检查配合when表达式即可实现类型判断,针对Map<String,String>需要额外处理JVM泛型擦除问题:先判断为Map类型后,遍历所有键值对确认键、值均为String类型即可。

补全后的完整代码如下:

fun <T> checkType(args: T): String {
    return when (args) {
        is Int -> "Yes! it's Integer"
        is String -> "Yes! it's String"
        is Boolean -> "Yes! it's Boolean"
        is Double -> "Yes! it's Double"
        is List<*> -> "Yes! it's List"
        is Map<*, *> -> {
            val matchStringMap = args.all { entry -> entry.key is String && entry.value is String }
            if (matchStringMap) "Yes! it's Map<String, String>" else "Unsupported type"
        }
        else -> "Unsupported type"
    }
}

fun main() {
    println(
        """
        '[10, 9, 8 , 6]' is List? ${checkType(listOf(10, 9, 8, 6))}
        'This is Kotlin' is String? ${checkType("This is Kotlin")}
        'True' is Boolean? ${checkType(true)}
        '10.01' is Double? ${checkType(10.01)}
        '10' is Integer? ${checkType(10)}
        '{"key":"value"}' is Map<String,String>? ${checkType(mapOf("key" to "value"))}
    """.trimIndent()
    )
}

运行验证

运行main函数输出结果如下:

'[10, 9, 8 , 6]' is List? Yes! it's List
'This is Kotlin' is String? Yes! it's String
'True' is Boolean? Yes! it's Boolean
'10.01' is Double? Yes! it's Double
'10' is Integer? Yes! it's Integer
'{"key":"value"}' is Map<String,String>? Yes! it's Map<String, String>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:15:48