首页 > 解决方案 > 如何检查 Kotlin 变量的类型

问题描述

我正在编写一个Kotlin程序,type变量在哪里,inferred但后来我想知道这个变量存储什么类型的值。我尝试了以下但它显示以下错误。

Incompatible types: Float and Double

val b = 4.33 // inferred type of what
if (b is Float) {
    println("Inferred type is Float")
} else if (b is Double){
    println("Inferred type is Double")        
}

标签: variablesif-statementkotlin

解决方案


您可以使用b::class.simpleName 它将对象类型返回为String.

您不必初始化变量的类型,稍后您想检查变量的类型。

    fun main(args : Array<String>){
        val b = 4.33 // inferred type of what
        when (b::class.simpleName) {
        "Double" -> print("Inferred type is Double")
        "Float" -> print("Inferred type is Float")
        else -> { // Note the block
            print("b is neither Float nor Double")
        }
    }
}

推荐阅读