美文网首页
Kotlin 学习小结(reified关键字探索)

Kotlin 学习小结(reified关键字探索)

作者: 码农小龙 | 来源:发表于2020-03-07 14:36 被阅读0次

通过泛型及reified关键字实现同一方法不同类型的返回值
如:

    inline fun <reified T> Int.cast(): T {
        return when (T::class) {
            Int::class -> this as T
            Double::class -> toDouble() as T
            Float::class -> toFloat() as T
            String::class -> toString() as T
            else -> throw Exception("not support")
        }
    }

测试下方法

    @Test
    fun test() {
        val float: Float = 12.cast()
        println(float)
        val double: Double = 13.cast()
        println(double)
        val int: Int = 14.cast()
        println(int)
        val string: String = 15.cast()
        println(string)
    }

打印结果为

12.0
13.0
14
15

相关文章

网友评论

      本文标题:Kotlin 学习小结(reified关键字探索)

      本文链接:https://www.haomeiwen.com/subject/eadcdhtx.html