如何检查 Kotlin 变量的类型

imG*_*mGs 7 variables if-statement kotlin

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

Incompatible types: Float and Double
Run Code Online (Sandbox Code Playgroud)
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")        
}
Run Code Online (Sandbox Code Playgroud)

Rav*_*wat 10

您可以使用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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Irc*_*ver 2

您遇到此错误是因为您的b变量已经是Double,所以无论如何它都不能是Float。如果您想测试您的if语句,您可以更改变量初始化,如下所示:

val b: Number = 4.33 // Number type can store Double, Float and some others
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你可以ifwhen语句替换

when (b) {
    is Float -> println("Inferred type is Float")
    is Double -> println("Inferred type is Double")
    else -> //some default action
}
Run Code Online (Sandbox Code Playgroud)