Get type of a variable in Kotlin

女生的网名这么多〃 提交于 2020-06-10 02:09:51

问题


How can I find the variable type in Kotlin? In Java there is instanceof, but Kotlin does not exist:

val properties = System.getProperties() // Which type?

回答1:


You can use the is operator to check whether an object is of a specific type:

val number = 5
if(number is Int) {
   println("number is of type Int")
}

You can also get the type as String using reflection:

println("${number::class.simpleName}")    // "Int"
println("${number::class.qualifiedName}") // "kotlin.Int"

Please note:

On the Java platform, the runtime component required for using the reflection features is distributed as a separate JAR file (kotlin-reflect.jar). This is done to reduce the required size of the runtime library for applications that do not use reflection features. If you do use reflection, please make sure that the .jar file is added to the classpath of your project.

Source: https://kotlinlang.org/docs/reference/reflection.html#bound-class-references-since-11



来源:https://stackoverflow.com/questions/45165143/get-type-of-a-variable-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!