variables - 如何检查 Kotlin 变量的类型

标签 variables if-statement 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")        
}

最佳答案

推断类型意味着编译器已检索到对象的数据类型。

所以,val b = 4.33是 Double(基于 kotlin 编译器)。

所以它假设'b'到处都是Double。

如果您希望将变量分配给不同的数据类型,则必须使用 Any类(class)

喜欢

fun main(vararg abc : String) {
    var b : Any = 4.33 // inferred type of what
    println(b)

    if(b is Float) {
        println("Float")
    }

    else if(b is Double) {
        println("Double")
    }

    b = "hello"
    println(b)
    if(b is String) {
        println("String")
    }
}

输出在
4.33
Double
hello
String

这里AnyObject 相同来自java的类,可以保存任何类型的数据,你必须照顾对象类型

关于variables - 如何检查 Kotlin 变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696294/

相关文章:

php - 在 PHP 中清理合法变量名称的字符串

javascript - Javascript 中的返回值和变量范围

javascript - (背景颜色)开关不起作用

c++ - 如何在所需值之前输出学生姓名?

spring-boot - 如何在单元测试中从依赖注入(inject)容器中获取实例?

android - View 绑定(bind)出现错误 : incompatible with attribute android:visibility

java - Java中的最终变量操作

python - 从在所述函数中定义的另一个函数中更改函数的局部变量.. Python

excel - 从数字中识别文本的 Google 表格/Excel 公式

list - Kotlin 生成没有重复元素的列表的排列(按顺序)