android - 如何在 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
}```
解决方案
// 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
推荐阅读
- javascript - 客户端表单验证未发生 + 无法编辑表单元素
- angular - routerLink 未导航到新页面
- linux - 缺少从 java 应用程序创建文件夹的权限
- tensorflow2.0 - 您输入的数据用完了
- javascript - 更新 html 标签中的动态 api 值的最佳实践
- python - 使用 scikit-learn (sklearn),如何处理线性回归的缺失数据(依赖变量 y)?
- cordova - javascript中的Cordova Admob免费插件-插件不起作用
- python - Mac OS 上的 PIP 安装版本问题
- android-studio - 在 Android Studio 中查找并替换带有间隙/通配符的单词
- database - Cassandra 无法从 CSV 导入