我正在写一个 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
这里
Any
与 Object
相同来自java的类,可以保存任何类型的数据,你必须照顾对象类型
关于variables - 如何检查 Kotlin 变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696294/