首页 > 解决方案 > 如何在 kotlin 上捕获参数的数据类型?

问题描述

我有一个以 args 为参数的通用“getResult”函数,然后程序怎么知道 args 是否具有 Int 类型、String 类型或不是这两种数据类型?

// Coming Soon
fun main() {
    val stringResult = getResult("Kotlin")
    val intResult = getResult(100)

    // TODO 2
    println()
}

// TODO 1
fun <T> getResult(args: T): Int {
    return 0
}```

标签: androidgenericskotlin

解决方案


// Coming Soon
fun main() {
    val stringResult = getResult("Kotlin")
    val intResult = getResult(100)
    val bolResult = getResult(true)
    // TODO 2
    println("$stringResult and $intResult now $bolResult")
}

// TODO 1
fun <T> getResult(args: T): Int {
    when(args){
        is String -> {
            return args.length
        }
        is Int ->{
            return args*5
        }
    }
    return 0
}```

That I think my Answer but I should check again with different cases

推荐阅读