variables - 如何检查 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")
}
解决方案
您可以使用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")
}
}
}
推荐阅读
- python - Python 多处理和 NLTK wordnet 路径相似性
- mysql - MySQL 触发器未正确检查变量
- javafx - 在 RichTextFX CodeArea 中保持缩进
- python - 连续运行一个脚本,同时安排另一个
- regex - 使用 regex shell 命令交换文件所有行中的字符串和数字排序
- c++ - 可变参数模板参数的问题
- javascript - 大表的Angular 6性能问题
- sql - 如何摆脱由于 PLSQL linesize 大于每行中的数据而导致的空格?
- c# - 在不同视图中使用下拉列表中的文本值
- node.js - nodejs s3存储桶上传脚本可重用