【问题标题】:How to catch the data type of the argument on kotlin?如何在 kotlin 上捕获参数的数据类型?
【发布时间】:2019-09-04 21:46:40
【问题描述】:

我有一个以 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
}```

【问题讨论】:

    标签: android generics kotlin


    【解决方案1】:

    如果要获取具体的类型,可以使用反射

     val foo = ...
      println("${foo::class.simpleName}")    // returns the generic type
    

    但是反射是相当昂贵的。不确定您的用例是什么,但如果您知道要传递给该函数的类型,您可以返回泛型类型作为结果

    fun <T> getResult(args: T): T {
    
    }
    

    然后检查它是否是这些实例之一。即一个字符串或一个int

    val result = getResult(1)
    when(result) {
        is String -> { do a thing }
        is Int -> { do a thing }
     }
    

    【讨论】:

    • 我想在这种情况下使用此代码:如果类型是 String,它将具有 String 长度返回值,如果它具有 Int 类型,它将返回 args * 5 值,或者如果不是两者,它将返回返回 0
    • 感谢您的帮助
    • 您是否传入自定义类型?不会出现同时传入 String 和 Int 的情况,除非它们包含在其他类中。
    【解决方案2】:
    // 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
    

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多